【问题标题】:Unit test with mocha + chai always passedmocha + chai 的单元测试总是通过
【发布时间】:2018-04-17 02:43:22
【问题描述】:

我尝试使用 'mocha' 和 'chai' 进行单元测试,但我的测试结果有问题,它总是通过。 请看一下。

UnitTest.spec.ts

import PostgresService from "../src/Services/PostgresService"
import {expect} from "chai"
import 'mocha'

describe('Postgres Override Test function', () => {
    it('should return any number but not zero', async () => {
        let client = new PostgresService();
        let result = await client.getLatestCMD("Servo");   
        try{
            console.log("Type : " + typeof(result));
            console.log("Value : " + result.rows[0].id);
            expect(result.rows[0].id).to.equal(0)        
        }catch(error){

        }
    })
})

【问题讨论】:

  • 移除 try catch 块
  • @LiroyLeshed.com 成功了!但为什么呢?
  • 许多单元测试框架通过抛出异常来指示错误。如果您静默地捕获异常,您实际上已经禁用了信号机制。

标签: unit-testing typescript mocha.js bdd chai


【解决方案1】:

使用ASYNCHRONOUS CODE时,需要在回调中完成

例子

您需要将 done 声明为it 的参数。

it('description', (done) => {
    expect((err, result) => {
    if (err) done(err);
    else done();
 })
})

【讨论】:

    【解决方案2】:

    删除 try catch 块以实际运行您的 expect 函数。

    如果您的 try 块返回错误,JavaScript 解释器将转到 catch 块,因此前者永远不会运行。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 1970-01-01
      • 2018-11-05
      • 2018-01-31
      • 2018-03-22
      • 2019-02-03
      • 2020-12-07
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多