Mocha js测试字符串不相等时不显示diff

Mocha js tests not showing diff when strings not equal

本文关键字:显示 diff 不相等 js 测试 字符串 Mocha      更新时间:2023-09-26

我有一个简单的单元测试来断言字符串是正确的,但它只显示失败的测试名称,而不是预期结果和实际结果的差异。例如,这里有一些愚蠢的测试代码:

describe('stackoverflow', function(){
    it('should be simple', function() {
        var someValue = 'A' + 1 + 2;
        assert.equal('A3', someValue);
    });
});

输出不是很有帮助:

$ mocha
  stackoverflow
    1) should be simple   <--- this line is red

是的,我可以看出哪项测试失败了,但我不太清楚为什么。我想看看这样的东西:

$ mocha
  stackoverflow
    1) should be simple
       Expected: 'A3'
       Actual  : 'A12'

我做错什么了吗?

这是因为我后来进行了另一个测试,没有设置超时(因为它非常慢),并使用异步模式,但我没有调用done()

下面是test.js,它演示了我看到的问题(我已经删除了所有不必要的垃圾):

var assert = require("assert");
describe('basic', function(){
    it('should be simple', function() {
        var someValue = 'A' + 1 + 2;
        assert.equal('A3', someValue);
    });
});
describe('slow', function(){
    it('should not explode', function(done) {
        this.timeout(0); // because it takes ages
    });
});

解决方案只是确保我在异步测试中调用done():

var assert = require("assert");
describe('basic', function(){
    it('should be simple', function() {
        var someValue = 'A' + 1 + 2;
        assert.equal('A3', someValue);
    });
});
describe('slow', function(){
    it('should not explode', function(done) {
        this.timeout(0); // because it takes ages
        done();
    });
});