Carlos Araya
Carlos Araya

Reputation: 881

Why is my mocha/should Array throwing test failing?

The following code snippet is very simple (from https://mochajs.org/#synchronous-code). It feels stupidbut, why does [1,2,3] evaluates to undefined when used with literal notation, and not when used in a myArray variable?

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
    })
  })
})

When I run the test, line 'b' fails as follows:

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 ...

I would a appreciate some light on this disturbing, but surely easy-to-answer, question. Cheers.

Upvotes: 0

Views: 122

Answers (1)

Nix
Nix

Reputation: 58602

Fiddle that allows you to test it out:

Your missing a semi-colon and it's disrupting your tests. I'm not an expert at the edge cases but you can read about them online: 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);  

Upvotes: 2

Related Questions