javascript Mocha 测试因断言错误而失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30507170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:17:56  来源:igfitidea点击:

Mocha Test Fails with AssertionError

javascriptunit-testingtestingmocha

提问by user3452075

In JUnit (Java) the result of a unit test is either a succes, failure or error.

在 JUnit (Java) 中,单元测试的结果是成功、失败或错误。

When i try to run a test with Mocha i either get a succes or assertion error.

当我尝试使用 Mocha 运行测试时,我要么成功,要么断言错误。

Is is normally to get an AssertionError for failure tests? (shouldn't it just be called an failure and not an error?)

通常是为了失败测试获得 AssertionError 吗?(难道它不应该只是被称为失败而不是错误吗?)

AssertionError: -1 == 2 + expected - actual

断言错误:-1 == 2 + 预期 - 实际

What about testing asynchronous code? When my tests fail i get an Uncaught eror? Is that normal?

测试异步代码怎么样?当我的测试失败时,我会收到一个未捕获的错误?这是正常的吗?

Like this:

像这样:

Uncaught Error: expected 200 to equal 201

未捕获的错误:预期 200 等于 201

回答by Louis

What you are describing is the normal behavior for Mocha. This code illustrates what happens if you do not try to trap exceptions in asynchronous code (even raised by assertion failures) and what you can do if you want to avoid the uncaught exception message:

您所描述的是摩卡的正常行为。这段代码说明了如果您不尝试在异步代码中捕获异常(甚至由断言失败引发)会发生什么,以及如果您想避免未捕获的异常消息,您可以做什么:

var assert = require("assert");

it("fails with uncaught exception", function (done) {
    setTimeout(function () {
        assert.equal(1, 2);
        done();
    }, 1000);
});

it("fails with assertion error", function (done) {
    setTimeout(function () {
        try {
            assert.equal(1, 2);
            done();
        }
        catch (e) {
            done(e);
        }
    }, 1000);
});

The code above produces this output:

上面的代码产生这个输出:

  1) fails
  2) fails

  0 passing (2s)
  2 failing

  1)  fails:
     Uncaught AssertionError: 1 == 2
      at null._onTimeout (/tmp/t2/test.js:5:16)
      at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

  2)  fails:
     AssertionError: 1 == 2
      at null._onTimeout (/tmp/t2/test.js:13:20)
      at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)