2016-03-06 74 views
0

我使用should.js框架(v8.2.x)进行单元测试,并且一直在玩一些非常基本的测试。然而,我遇到了这个测试失败的问题,这一直困扰着我。现在根据自己的githubshould(something)something.should通常返回相同的事情Should.js - equals方法中的不一致should.equals

should.equal(add('1', '1'), '2'); // passes 
add('1', '1').should.equal('2')  // fails! 

我定义这个虚拟函数测试,add

var add = function(a, b) { 
    if (isNaN(a) || isNaN(b)) { 
    throw new Error('One of the arguments is not a number'); 
    } 
    return +a + +b 
}; 

现在我这里还有我的假人测试,但没有关于差异的其他信息。

根据它们的API documentation,should.equalassert.equal相同。但这种测试通过对我来说:

assert.equal(add('1','1'), '2'); // passes 

所以我有三个问题:

  1. 为什么add('1', '1').should.equal('2')不能通过?
  2. 为什么两种用法会产生不同的结果?
  3. 为什么文档说should.equalsassert.equals实际上有不同的行为?
+1

我猜,一个是使用''==,另一个是使用''===。 'add'函数返回一个'Number',你正在比较一个'string'。也许所做的类型强制是不同的?如果你做'add('1','1')should.equal(2)',会发生什么? –

+0

什么@ChrisTavares说,每当你处理的测试号VS字符串你应该看看是如何执行的测试,我会假设测试将返回'“11''为'” 1' +“1''但很明显,这不是字面意思。 – brod

+0

@ChrisTavares是的,'equals'应该在javascript中使用'=='和'1 =='1''。还有'strictEquals'使用'==='。 'add('1','1')。should.equal(2)'确实通过。 @brod如果你看一下'add',我使用的是一元'+'经营者强迫他们数= –

回答

0

回答你的问题,你错了什么。

现在根据他们的github,应该(something)和something应该通常返回相同的东西,但没有关于差异的额外信息。

should(something) and something.should是的通常是一样的。但是你使用了should.equal,文档没有提到它与其他方法的等价性。这只是copy of的node.js自己assert.equal

为什么加( '1', '1')。should.equal( '2')不及格?

因为docs明确表示它在内部使用===。

为什么两种用法会产生不同的结果?

因为这是不同的方法,并且无处说它应该是平等的。

为什么文档说,当它们实际上有不同的行为时,should.equals和assert.equals是一样的?

$ node 
> var should = require('.') 
undefined 
> var assert = require('assert') 
undefined 
> var add = function(a, b) { 
... if (isNaN(a) || isNaN(b)) { 
.....  throw new Error('One of the arguments is not a number'); 
..... } 
... return +a + +b 
... }; 
undefined 
> should.equal(add('1', '1'), '2'); 
undefined 
> assert.equal(add('1', '1'), '2'); 
undefined 

所以尝试你有明确自己做错了什么:在should.js存在should.equal(a, b)这是一样的assert.equal。也存在something.should.equal(other)它采用===内部(因为存在.eql其做深平等检查),也should(somethng).equal(other)相同something.should.equal(other)(而不是标准的包装)。

希望它会清楚。