gpt4 book ai didi

node.js - Nodejs Jest 单元测试无法从 Mongodb 查找、findOne 内部返回值

转载 作者:搜寻专家 更新时间:2023-10-31 23:56:33 24 4
gpt4 key购买 nike

我正在使用 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 ".

最佳答案

unitMethodTestasync所以你必须 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在第一行

关于node.js - Nodejs Jest 单元测试无法从 Mongodb 查找、findOne 内部返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com