Node.js Sinin没有返回函数调用次数的正确数字
我有一个代码如下:Node.js Sinin没有返回函数调用次数的正确数字,node.js,unit-testing,mocha.js,sinon,Node.js,Unit Testing,Mocha.js,Sinon,我有一个代码如下: public async cleanUpCachedData(){ const queries = await this._searchesDatastore.getArchivedSearches(); queries.forEach(async query => { try{ // try catch for each is neccessary await this.ha
public async cleanUpCachedData(){
const queries = await this._searchesDatastore.getArchivedSearches();
queries.forEach(async query => {
try{
// try catch for each is neccessary
await this.handleCacheCleanup("columns", query._id);
console.log("################")
await this.handleCacheCleanup("json", query._id);
console.log("################")
await this.handleCacheCleanup("stix", query._id);
console.log("################")
await this.handleCacheCleanup("summary", query._id);
console.log("################")
await this.handleCacheCleanup("timechart", query._id);
console.log("################")
我写了一个测试:
it("Successful handling cache data clean up process", async () => {
const searchDatastoreObj = searchesDatastore;
const getArchivedSearchesStub = sandbox
.stub(searchDatastoreObj, "getArchivedSearches")
.returns([{_id: "11111"}]);
const obj = initCache(
loggingService,
searchesDatastore,
resultsDatastoreObj,
);
const test = sandbox
.stub(obj, "handleCacheCleanup").returns(true)
await obj.cleanUpCachedData();
expect(getArchivedSearchesStub.calledOnce).to.be.true;
expect(test.callCount).to.equal(5);
});
正如你所说,我有5个handleCacheCleanup函数调用,我可以看到打印了5次,但测试声称它运行了两次
1) test cache cleanup by Total disk space
Successful handling cache data clean up process:
AssertionError: expected 2 to equal 5
+ expected - actual
-2
+5
我对任何想法都感到困惑即使您将其作为异步查询,
查询。forEach
被视为同步,承诺解决/拒绝被忽略。可能的调整方法是使用Promise.all()
它执行了对控制台日志记录点的5个调用,但是测试用例在所有承诺得到解决之前就完成了
forEach
不是异步的,所以它被执行了,但没有等待内部的所有承诺都完成。更新后感谢它的工作,但请解释一下为什么我的没有返回5个调用?我还是有点困惑
await Promise.all(queries.map(query => {
try{
// try catch for each is neccessary
await this.handleCacheCleanup("columns", query._id);
console.log("################")
await this.handleCacheCleanup("json", query._id);
console.log("################")
await this.handleCacheCleanup("stix", query._id);
console.log("################")
await this.handleCacheCleanup("summary", query._id);
console.log("################")
await this.handleCacheCleanup("timechart", query._id);
console.log("################")
} catch (e) {}
})