Jest: How to mock one specific method of a class

后端 未结 7 1878
暗喜
暗喜 2020-11-30 23:43

Let\'s suppose I have the following class:

export default class Person {
    constructor(first, last) {
        this.first = first;
        this.last = last         


        
7条回答
  •  长情又很酷
    2020-12-01 00:36

    Using jest.spyOn() is the proper Jest way of mocking a single method and leaving the rest be. Actually there are two slightly different approaches to this.

    1. Modify the method only in a single object

    import Person from "./Person";
    
    test('Modify only instance', () => {
        let person = new Person('Lorem', 'Ipsum');
        let spy = jest.spyOn(person, 'sayMyName').mockImplementation(() => 'Hello');
    
        expect(person.sayMyName()).toBe("Hello");
        expect(person.bla()).toBe("bla");
    
        // unnecessary in this case, putting it here just to illustrate how to "unmock" a method
        spy.mockRestore();
    });
    

    2. Modify the class itself, so that all the instances are affected

    import Person from "./Person";
    
    beforeAll(() => {
        jest.spyOn(Person.prototype, 'sayMyName').mockImplementation(() => 'Hello');
    });
    
    afterAll(() => {
        jest.restoreAllMocks();
    });
    
    test('Modify class', () => {
        let person = new Person('Lorem', 'Ipsum');
        expect(person.sayMyName()).toBe("Hello");
        expect(person.bla()).toBe("bla");
    });
    

    And for the sake of completeness, this is how you'd mock a static method:

    jest.spyOn(Person, 'myStaticMethod').mockImplementation(() => 'blah');
    

提交回复
热议问题