1

We mock our modules using __mocks__. I'd like to spyOn a module function in my test but it doesn't seem to be working. Related question, I'd also like to override a mocked module function for a test (ie throw an exception). How can I do this?

├──__mocks__ 
|  └──DB-Utils.js
|  └──controllers
|       └──myController.js
├──node_modules

__mocks__/DB-Utils.js:

const { MyController } = require('./controllers/myController');
module.exports = {
  MyController,
};

__mocks__/controllers/myController.js:

class MyController {
  async setAvailability(id, availability) {
    return true;
  }
}

module.exports = {
  MyController,
};

test.spec.js:

const { MyController } = require('DB-Utils');

const myController = new MyController();

  describe('Register Tests', () => {
    fit('myController setAvailability', async () => {
      ---code that calls a class that ends up calling myController.setAvailability---
      expect(myController.setAvailability).toHaveBeenCalledWith('foo', 'bar');
    });
  });

My tests pass in that the mock myController is called, however it fails the toHaveBeenCalledWith with an error of Number of calls: 0

How can I spy setAvailability?

For the related question I'd also like to be able to do something like the following:

  describe('Register Tests', () => {
    fit('myController setAvailability throws', async () => {
      jest.spyOn(myController, 'setAvailability').mockImplementation(() => {
        throw new Error()
      });
      expect(---code that calls a class that ends up calling myController.setAvailability---).toThrow();
    });
  });
jstokes
  • 211
  • 2
  • 6

0 Answers0