Sinin 没有 return 函数被调用次数的正确数字

Sinin does not return the right number forhow many times a function got called

我有一个代码如下:

 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

我真的一头雾水

即使您将其设置为异步,queries.forEach 也会被视为同步,而 Promise resolve/rejection 会被忽略。可能的调整方法是使用 Promise.all().

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) {}
})

它执行了对控制台日志记录点的 5 次调用,但测试用例在所有承诺解决之前完成。 forEach 不是异步的,所以它被执行了,但没有等待里面的所有承诺完成。