我正在尝试测试在node.js应用中命中路由时是否调用了中间件函数。我正在使用jest
和supertest
编写单元测试。中间件功能作为req.directory.getName()
附加到请求。
getName()
调用外部API。
我不希望测试实际调用真正的中间件功能,以便在测试中不调用外部API。我仅测试连接到请求的directory.getName()
函数是否被调用。
我该如何模拟中间件函数以进行测试,以使req.directory.getName()
是一个伪函数,实际上并没有调用任何API?
这是我目前所拥有的:
const app = require('../src/app');
const request = require('supertest');
test('gets user name from directory', () => {
return request(app)
.post('/users/add')
.send({ id: '1' })
.expect(202);
});