How to mock es6 class using Jest

前端 未结 2 500
暖寄归人
暖寄归人 2020-12-15 17:29

I am attempting to mock a class Mailer using jest and I can\'t figure out how to do it. The docs don\'t give many examples of how this works. The process is the

2条回答
  •  忘掉有多难
    2020-12-15 17:45

    Just for Googlers and future visitors, here's how I've setup jest mocking for ES6 classes. I also have a working example at github, with babel-jest for transpiling the ES module syntax so that jest can mock them properly.

    __mocks__/MockedClass.js

    const stub = {
      someMethod: jest.fn(),
      someAttribute: true
    }
    
    module.exports = () => stub;
    

    Your code can call this with new, and in your tests you can call the function and overwrite any default implementation.

    example.spec.js

    const mockedClass = require("path/to/MockedClass")(); 
    const AnotherClass = require("path/to/AnotherClass");
    let anotherClass;
    
    jest.mock("path/to/MockedClass");
    
    describe("AnotherClass", () => {
      beforeEach(() => {
        mockedClass.someMethod.mockImplementation(() => {
          return { "foo": "bar" };
        });
    
        anotherClass = new AnotherClass();
      });
    
      describe("on init", () => {
        beforeEach(() => { 
          anotherClass.init(); 
        });
    
        it("uses a mock", () => {
          expect(mockedClass.someMethod.toHaveBeenCalled();
          expect(anotherClass.settings)
            .toEqual(expect.objectContaining({ "foo": "bar" }));
        });
      });
    
    });
    

提交回复
热议问题