如何测试下面的模块/功能,它调用外部api?如果我正在解除不再是单元测试的api,那就是调用集成或流量测试。我知道有这样的事情叫做模拟api,但它应该测试什么?我期待只有2个结果,它失败或成功。由于外部api已处理边缘情况(称名称参数不供应),我是否必须在我身边进行单元测试?
const request = require('request')
import PATH from './config/somewhere'
export const createUser = async (req, res, next) => {
try {
response = await request.post(`${PATH}/api/user/create`, {form: {name: req.body.name}})
res.json(response)
} catch(err) {
this.throw(err.message)
}
}
答案 0 :(得分:0)
请参阅: https://github.com/node-nock/nock
初始化测试时,您可以调用以下代码:
const nock = require('nock');
// ...
nock(`${PATH}/api/user`)
.post('/create')
.reply(200, { data: 'foo' });
// ...
// All calls to request from here will be intercepted by nock