3

I am using sinon.js to test my API. I would like to test the order from my helper functions that are being called.

controller.js

exports.controllerFunction = async (req, res) => { 

    const function1Results = await function1(paramm);

    const function2Results = await function2(param, function1Results);

    return res.send(function2Results);
};

helpers.js

exports.function1 = function(param) {
 return param;
}

exports.function2 = function(param, func) {
 return param;
}

unitTest.js

const controller = require('./controller.js')
const helpers = require('./helpers.js')

describe('Unit test cycle', () => {
 beforeEach(() => {
  // Spies
  sinon.spy(controller, 'controllerFunction');
  sinon.spy(helpers, 'function1');
  sinon.spy(helpers, 'function2');

  // Function calls
  controller.controllerFunction(this.req, this.res)
 })

 afterEach(() => {
  sinon.restore();
 })

 this.req = {}
 this.res = {}

 it('should call getAvailability', (done) => {
  expect(controller.controllerFunction.calledOnce).to.be.true
  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true
 });
})

expect(controller.controllerFunction.calledOnce).to.be.true

is returning in as true

  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true

and is coming in as false.

Because my helper functions are being used in the controller they should be called as well, yet they are not.

So how do I test if my helper functions are being called as well when the controller is tested?

Darron
  • 323
  • 4
  • 14

1 Answers1

0

I will try to give a shot. Since your function is async I think your block for testing should be made to await for it.

I recommend moving the function call inside the it block of commands. beforeEach is usually used for setup, afterEach is used to clear some data/mocks (also known as tear).

Try

it('should call getAvailability', async (done) => {
  // When
  await controller.controllerFunction(this.req, this.res)
  // Assert
  expect(controller.controllerFunction.calledOnce).to.be.true
  expect(helpers.function1.calledOnce).to.be.true
  expect(helpers.function2.calledOnce).to.be.true
  done && done()
 });

Don't forget to remove the function call from beforeEach.

ssbarbee
  • 1,626
  • 2
  • 16
  • 24
  • Nice try. This was the error I got: understood that it now throws an exception Error: Resolution method is overspecified. Specify a callback * or * return a Promise; not both. – Darron Dec 23 '19 at 13:50
  • Thanks for the attempt but that didn't do it. – Darron Dec 27 '19 at 14:17