Jest: How to mock one specific method of a class

后端 未结 7 1867
暗喜
暗喜 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

    If you are using Typescript, you can do the following:

    Person.prototype.sayMyName = jest.fn().mockImplementationOnce(async () => 
            await 'my name is dev'
    );
    

    And in your test, you can do something like this:

    const person = new Person();
    const res = await person.sayMyName();
    expect(res).toEqual('my name is dev');
    

    Hope this helps someone!

提交回复
热议问题