0

我们使用 .mock 模拟我们的模块__mocks__。我想spyOn在我的测试中添加一个模块功能,但它似乎不起作用。相关问题,我还想覆盖一个模拟模块函数进行测试(即抛出异常)。我怎样才能做到这一点?

├──__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');
    });
  });

我的测试通过了模拟 myController 被调用,但是它失败toHaveBeenCalledWith并出现错误Number of calls: 0

如何监视 setAvailability?

对于相关问题,我还希望能够执行以下操作:

  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();
    });
  });
4

0 回答 0