Jest: How to mock one specific method of a class

后端 未结 7 1884
暗喜
暗喜 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:21

    I don't see how the mocked implementation actually solves anything for you. I think this makes a bit more sense

    import Person from "./Person";
    
    describe("Person", () => {
      it("should...", () => {
        const sayMyName = Person.prototype.sayMyName = jest.fn();
        const person = new Person('guy', 'smiley');
        const expected = {
          first: 'guy',
          last: 'smiley'
        }
    
        person.sayMyName();
    
        expect(sayMyName).toHaveBeenCalledTimes(1);
        expect(person).toEqual(expected);
      });
    });
    

提交回复
热议问题