0

假设我有一个 POST 端点/user/:id,这个端点在内部调用一个函数getUserData(id),然后将结果返回给调用者,调用者在JSON.stringify()ing 之后又返回输出。

现在,我需要确保getUserData(id)至少调用一次。getUserData(id)当我使用chai-http向服务器发出发布请求时,如何存根/间谍功能?这甚至是正确的方法吗?

4

1 回答 1

0

我将教程从https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai调整为准系统servertest您可以使用它来进行基本的 API 测试。

正如 Mr.Phoenix 所说,您无需深入handler了解 .

以下是可用于执行此测试的 2 个文件:

index.js

const express = require('express')
const app = express()



app.get('/material',(req, res)=>{
  res.json([])
  //res.json(['stone', 'wood'])
})

function getUserData(id){
  return 42
}

const port = 3031

app.listen(port, function(err){
  console.log("Listening on port: " + port)
})
module.exports = app

测试.js

process.env.NODE_ENV = 'test'
// const Material = require('./materials') // conroller
const chai = require('chai')
const chaiHttp = require('chai-http')
const server = require('./index')
const should = chai.should()


chai.use(chaiHttp)



describe('/GET material', () => {
  it('it should get all the materials', (done)=>{
    chai.request(server)
    .get('/material')
    .end((err, res) => {
      res.should.have.status(200)
      res.body.should.be.a('array')
      res.body.length.should.be.eql(0) // start empty
      done()
    })
  })
})
于 2017-04-12T19:56:48.853 回答