【问题标题】:Testing in async functions. Test passing when should be failing在异步函数中进行测试。测试通过什么时候应该失败
【发布时间】:2020-12-04 15:35:06
【问题描述】:

大家好,这个测试应该失败,但它通过了,同时也抛出了断言错误。

 describe('Testing getAllrecipes',()=>{
  it('1. Test get All Recipes',(done)=>{
    var uri = "mongodb://localhost:27017";
    var dbname = "testRecipes";
    var collectionName = "testCollectionClean";
    let driver = new MongoDriver(uri,dbname,collectionName);
    driver.dropCollection(); //Clean collection for testing... NEVER CALL ON PRODUCTION COLLECTION
    driver.addMockData();

    driver.getAllRecipe().then((promise)=>{
        assert.deepEqual(promise,'fake news')
        done();
    }).catch((e)=>{
        console.log(e);
        done();
    });
 });
})

控制台:

AssertionError: expected [] to deeply equal 'fake news'
{
showDiff: true,
actual: [],
expected: 'fake news'
}
✓ 1. Test get All Recipes
    
8 passing (60ms)

如何让测试返回失败?

【问题讨论】:

标签: javascript node.js chai


【解决方案1】:

catch子句中,你需要调用done报错,

    }).catch((e)=>{
        console.log(e);
        done(e);
    });

【讨论】:

  • 谢谢我的家伙!这行得通!无论如何,如果没有 catch 块,测试会失败吗?
  • 根据你的 mocha/chai 版本,你可以在没有 catch 块的情况下返回 promise,它会自己处理捕获错误。
  • 再次感谢@Shadab。你能否更具体地说明我会返回什么承诺?我会返回 driver.getAllRecipe().then(.......
【解决方案2】:

致所有正在寻找此答案的人。 Shadab 是正确的,我需要调用 done(e)。我的最终解决方案看起来像

return driver.getAllRecipe().then((promise)=>{
        assert.deepEqual(promise,'fake news')
    }).catch((e)=>{
        console.log(e);
        done(e);
        
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多