我对 Node 还很陌生,这是我第一次对应用程序进行单元测试。我在 Jest 方面做得很好,用 Jest 函数伪造请求,如下所示
// Create a fake request
const mockRequest = (sessionData, body) => ({
session: { data: sessionData },
body
});
// Create a fake response
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
const mockNext = () => {
const next = jest.fn();
return next;
};
Run Code Online (Sandbox Code Playgroud)
所以我可以像下面这样使用它们
doSomething(req, res, next);
expect(res.status).toHaveBeenCalledWith(201);
//or
expect(next).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
对于所有情况来说这已经足够了,直到我发现我的授权中间件包含几个参数,所以我无法传递虚假的 res 和 req ,如下所示
exports.isAllowedTo = (par1, par2) => …Run Code Online (Sandbox Code Playgroud) 我试图监视由另一个函数调用的函数,这两个函数都驻留在外部文件中并导入。
Funcs.spec.js:
import * as Funcs from './Funcs'
describe('funcA', () => {
it('calls funcB', () => {
jest.spyOn(Funcs, 'funcB')
Funcs.funcA()
expect(Funcs.funcB).toHaveBeenCalled()
}
}
Run Code Online (Sandbox Code Playgroud)
Funcs.js:
export const funcA = () => {
funcB()
}
export const funcB = () => {}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,间谍在 Funcs.js 的范围内不受尊重。我可以做什么来监视 funcB 以便我知道 funcA 调用了它?