Jest: How to mock one specific method of a class

后端 未结 7 1881
暗喜
暗喜 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:38

    Have been asking similar question and I think figured out a solution. This should work no matter where Person class instance is actually used.

    const Person = require("../Person");
    
    jest.mock("../Person", function () {
        const { default: mockRealPerson } = jest.requireActual('../Person');
    
        mockRealPerson.prototype.sayMyName = function () {
            return "Hello";
        }    
    
        return mockRealPerson
    });
    
    test('MyTest', () => {
        const person = new Person();
        expect(person.sayMyName()).toBe("Hello");
        expect(person.bla()).toBe("bla");
    });
    

提交回复
热议问题