0
以下代码片段非常简单(从https://mochajs.org/#synchronous-code)。它感觉很愚蠢,但为什么[1,2,3]
的计算结果与undefined
一起使用,而不是用于myArray
变量?为什么我的mocha /应该抛出Array测试失败?
Array
#indexOf()
1) Should return -1 when the value is not present
1) Array #indexOf() Should return -1 when the value is not present:
TypeError: Cannot read property 'indexOf' of undefined
... Error trace just points the line where it fails, nothing else ...
我一个赞赏这一令人不安的,但肯定容易回答,问题做了解释:
var assert = require('assert') // "mocha": "^3.0.2"
var should = require('should') // "should": "^11.1.0"
describe('Array', function() {
describe('#indexOf()', function() {
var myArray = [1, 2, 3]
it('Should return -1 when the value is not present', function() {
myArray.indexOf(0).should.equal(-1) // a - success
[1, 2, 3].indexOf(0).should.equal(-1) // b - fails test
})
})
})
当我运行测试,如下行“B”失败。干杯。
这个问题解释了为什么','应该使用函数表达式时使用。在这种情况下,每个'something.should.whatever()'返回一个对象。的确,应该扩展'something'的Object.prototype。无论如何,当“a”和“b”交换时,为什么测试通过? –
就像我说过的,我不是专家们对各种运行时如何解析javascript的问题,你问为什么它失败了,这是因为你没有终止你的声明。最佳做法是使用分号,我的猜测是当文字第二次折叠它并尝试做一个属性查找时,因为它看到'[xxx]'这是查找对象属性的一种方法。 **其猜测** – Nix