我正在通过console.log(data)获取数据;但它甚至没有从findOne方法内部返回req.params._id,而是从findOne方法外部返回
unitMethodTest = async (req, res, next) => {
await this.model.findOne({ _id: req.params._id }).exec((err, data) => {
if (err) {
console.log('===++++++ failed ');
return req.params._id;
}
else {
console.log(' Ok ')
// console.log(data);
return req.params._id; // Getting Error <--
}
});
// return req.params._id; // Test--2 Working fine <--
}
和我的测试代码在这里:-
const req = {
params: { _id: '5cc14019fa1c2c68ee7e17f9', },
body: 'body'
}, next = 'next', res = 'response';
test('First Method Testing Demo for req.params and req.body', () => {
// expect.assertions(1);
const dataTest = controller.unitMethodTest(req, res, next);
console.log(dataTest);
// console.log(dataTest);
expect(dataTest).toEqual("5cc14019fa1c2c68ee7e17f9");
})
我正在获取输出,如下所示
expect(received).toEqual(expected) // deep equality
Expected: "5cc14019fa1c2c68ee7e17f9"
Received: {}
53 | // console.log(dataTest);
54 | // // const dataTest = 11257;
> 55 | expect(dataTest).toEqual("5cc14019fa1c2c68ee7e17f9");
| ^
56 | done();
57 | // return controller.unitMethodTest(req, res, next).catch(e => expect(e).toEqual("5cc14019fa1c2c68ee7e17f9"));
58 | })
at Object.<anonymous> (server/unitTesting/caseload.test.ts:55:25)
console.log server/unitTesting/caseload.test.ts:52
Promise { <pending> }
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 18.606s
Cannot log after tests are done. Did you forget to wait for something
async in your test?
Attempted to log " Ok ".
答案 0 :(得分:1)
unitMethodTest
是async
,因此您必须在测试中await
,就像Jest在报告末尾告诉您的那样。
test('First Method Testing Demo for req.params and req.body', async () => {
const dataTest = await controller.unitMethodTest(req, res, next);
expect(dataTest).toEqual("5cc14019fa1c2c68ee7e17f9");
})
注意第一行的async