Rossi
Rossi

Reputation: 1

Simplest Chai Spies syntax

I'm having problems with Chai Spies. I have a hard time catching how the syntax works.

Here, I am trying the simple example. The myMap function which mimics the array.map method:

function myMap(inputArray, callback) {
  let newArr = [];

  for (i = 0; i < inputArray.length; i++) {
    let nEl = callback(inputArray[i]);
    newArr.push(nEl);
  };
  
  return newArr;
}

module.exports = myMap;

And the test:

const chai = require('chai');
const expect = chai.expect;
const spies = require('chai-spies');
chai.use(spies);

const myMap = require('../problems/my-map');

describe('function myMap', function () {
    const arr = [1, 2, 3];
    const cb1 = el => el*2;
    it('should return new array passed through callback', function () {
        
        expect(myMap(arr, cb1)).to.deep.equal([2, 4, 6]);
        
    });
    it('should preserve original array', function () {
        expect(arr).to.deep.equal([1,2,3]);
    });
    it('see if .map used on array', function () {
        expect(chai.spy.on(arr, 'map')).to.not.have.been.called();
    });
    it('callback called array.length times', function () {
        
        let spy1 = chai.spy(cb1);

        expect(spy1).to.have.been.called.exactly(arr.length);
    })
    
});

The test number 3 that uses spy works as intended, failing if I introduce .map method to the function. But the test number 4 gives the same result of having 0 callbacks while expecting 3. Surely I messed something with syntax, but I couldn't find any simple examples on the internet.

I'm using downgraded Chai version of 4.3.0, since there's some conflict with ES6 which I don't know how to resolve yet.

Upvotes: -1

Views: 74

Answers (1)

Rossi
Rossi

Reputation: 1

Ok, I've figured it out, thank you, jonrsharpe. The proper test goes like this:

it('callback called array length times', function () {
    let spy1 = chai.spy(cb1);
    myMap(arr, spy1);
    expect(spy1).to.have.been.called.exactly(arr.length);
});

You interchange callback with the chai.spy(callback), and then you can check what's happened to the spy. Have no idea why there's no such example of spy usage on the vast internet to let novices know how it works.

Upvotes: 0

Related Questions