【问题标题】:Why is my mocha/should Array throwing test failing?为什么我的 mocha/should Array throwing 测试失败?
【发布时间】:2016-09-22 19:38:08
【问题描述】:

下面的代码 sn -p 非常简单(来自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 ...

我希望能对这个令人不安但很容易回答的问题有所了解。干杯。

【问题讨论】:

    标签: javascript testing mocha.js should.js


    【解决方案1】:

    让你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);  
    

    【讨论】:

    • 这个问题解释了为什么在使用函数表达式时应该使用;。在这种情况下,每个something.should.whatever() 返回一个对象。实际上,应该只是扩展somethingObject.prototype。无论如何,为什么交换行'a'和'b'时测试通过了?
    • 就像我说的那样,我不是各种运行时如何解析 javascript 的专家,你问它为什么失败,这是因为你没有终止你的声明。最佳实践是使用分号,我的猜测是当文字出现在第二位时,它会折叠它并尝试进行属性查找,因为它看到了[xxx],这是一种在对象上查找属性的方法。 猜测
    猜你喜欢
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多