简体   繁体   中英

How to test a helper functions used in controller in Sinon.js

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM