我正在尝试为嵌套函数编写单元测试,如下所示:
myFunction.js
const anotherFunction = require('./anotherFunction.js')
module.exports = (app, io) => {
return (req, res) => {
const { id, value } = req.query
req.app.locals['target' + id].pwmWrite(value)
anotherFunction(app, io)
res.send({ value })
}
}
我想测试是否pwmWrite()
和anotherFunction()
被调用。
但是由于return (req, res) => {}
和导入的函数,我遇到了一些问题。
这是我的尝试,不起作用:
myFunction.test.js
test('should call pwmWrite() and anotherFunction()', async () => {
const app = {}
const io = { emit: jest.fn() }
const req = {
app: {
locals: {
target1: { pwmWrite: () => 25 }
}
}
}
}
expect.assertions(1)
expect(req.app.locals.target1.pwmWrite).toHaveBeenCalled()
await expect(myFunction(app, io)).resolves.toEqual(25)
})
答案 0 :(得分:0)
这是解决方案:
myFunction.js
:
const anotherFunction = require('./anotherFunction.js');
module.exports = (app, io) => {
return (req, res) => {
const { id, value } = req.query;
req.app.locals['target' + id].pwmWrite(value);
anotherFunction(app, io);
res.send({ value });
};
};
anotherFunction.js
:
module.exports = (app, io) => {
return 'do something';
};
单元测试:
jest.mock('./anotherFunction');
const myFunction = require('./myFunction');
const anotherFunction = require('./anotherFunction');
describe('test suites', () => {
test('should call pwmWrite() and anotherFunction()', () => {
const app = {};
const io = { emit: jest.fn() };
const id = '1';
const value = 'jest';
const req = {
query: { id, value },
app: {
locals: {
target1: { pwmWrite: jest.fn() }
}
}
};
const res = { send: jest.fn() };
myFunction(app, io)(req, res);
expect(anotherFunction).toBeCalledWith(app, io);
expect(req.app.locals.target1.pwmWrite).toBeCalledWith(value);
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/52845000/myFunction.spec.js
test suites
✓ should call pwmWrite() and anotherFunction() (5ms)
--------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------------|----------|----------|----------|----------|-------------------|
All files | 88.89 | 100 | 66.67 | 88.89 | |
anotherFunction.js | 50 | 100 | 0 | 50 | 2 |
myFunction.js | 100 | 100 | 100 | 100 | |
--------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.113s
以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52845000