NodeJS 控制器中的 Sinon mock Promise.all
Sinon mock Promise.all in NodeJS controller
在 NodeJS 控制器中使用 Promise.all。无法在 Sinon 中模拟这个。
控制器调用可重用方法来获取特定数据。但是,在一种情况下,我想将附加数据附加到数组中的每个结果。使用 Promise.all 来做到这一点。然而,尽管研究了这里的问题,但我还没有找到在这种情况下模拟 Promise.all 的解决方案。看了看setTimeout/done
周围的expect
。不确定需要在哪里调用 done
才能使其工作。
控制器
getItems()
...
let items = await Method.findAllByQuery(query);
if (userId && items) {
items = await Promise.all(items.map(async item => {
let tmpItem = item;
tmpItem.count = await AnotherMethod.countDocuments(query).exec();
return tmpItem;
}));
}
results.items = items;
诗乃测试
let stubMethod = sinon.stub(Method, 'findAllByQuery');
it('Should return a 200 if userId passed', async () => {
req.userId = '123456789';
stubMethod.returns(items);
await ShowController.getItems(req, res);
expect(res.statusCode).to.equal(200);
});
结果应该是200
。取而代之的是超时
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
您不需要存根 Promise.all
。您必须在函数中存根所有异步方法:Method.findAllByQuery(query)
和 AnotherMethod.countDocuments(query).exec()
:
let stubMethod = sinon.stub(Method, 'findAllByQuery');
let stubExec = sinon.stub();
let stubCountDocuments = sinon.stub(AnotherMethod, 'countDocuments');
stubCountDocuments.returns(stubExec);
it('Should return a 200 if userId passed', async () => {
req.userId = '123456789';
stubMethod.resolves(items);
stubExec.resolves(1);
await ShowController.getItems(req, res);
expect(res.statusCode).to.equal(200);
});
在 NodeJS 控制器中使用 Promise.all。无法在 Sinon 中模拟这个。
控制器调用可重用方法来获取特定数据。但是,在一种情况下,我想将附加数据附加到数组中的每个结果。使用 Promise.all 来做到这一点。然而,尽管研究了这里的问题,但我还没有找到在这种情况下模拟 Promise.all 的解决方案。看了看setTimeout/done
周围的expect
。不确定需要在哪里调用 done
才能使其工作。
控制器
getItems()
...
let items = await Method.findAllByQuery(query);
if (userId && items) {
items = await Promise.all(items.map(async item => {
let tmpItem = item;
tmpItem.count = await AnotherMethod.countDocuments(query).exec();
return tmpItem;
}));
}
results.items = items;
诗乃测试
let stubMethod = sinon.stub(Method, 'findAllByQuery');
it('Should return a 200 if userId passed', async () => {
req.userId = '123456789';
stubMethod.returns(items);
await ShowController.getItems(req, res);
expect(res.statusCode).to.equal(200);
});
结果应该是200
。取而代之的是超时
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
您不需要存根 Promise.all
。您必须在函数中存根所有异步方法:Method.findAllByQuery(query)
和 AnotherMethod.countDocuments(query).exec()
:
let stubMethod = sinon.stub(Method, 'findAllByQuery');
let stubExec = sinon.stub();
let stubCountDocuments = sinon.stub(AnotherMethod, 'countDocuments');
stubCountDocuments.returns(stubExec);
it('Should return a 200 if userId passed', async () => {
req.userId = '123456789';
stubMethod.resolves(items);
stubExec.resolves(1);
await ShowController.getItems(req, res);
expect(res.statusCode).to.equal(200);
});