以下代码段非常简单(来自https://mochajs.org/#synchronous-code)。感觉很愚蠢,但为什么[1,2,3]
在使用文字符号时会评估为undefined
,而在myArray
变量中使用时却不会评估?
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'失败如下:
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 ...
我会对这个令人不安但肯定容易回答的问题有所了解。欢呼声。
答案 0 :(得分:2)
小提琴允许你test it out:
你遗漏了一个分号并且它破坏了你的测试。我不是边缘案件的专家,但您可以在线阅读它们:Why should I use a semicolon after every function in javascript?
myArray.indexOf(0).should.equal(-1) ;
[1, 2, 3].indexOf(0).should.equal(-1);