Jest: How to mock one specific method of a class

后端 未结 7 1869
暗喜
暗喜 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:25

    Not really answer the question, but I want to show a use case where you want to mock a dependent class to verify another class.

    For example: Foo depends on Bar. Internally Foo created an instance of Bar. You want to mock Bar for testing Foo.

    Bar class

    class Bar {
      public runBar(): string {
        return 'Real bar';
      }
    }
    
    export default Bar;
    

    Foo class

    import Bar from './Bar';
    
    class Foo {
      private bar: Bar;
    
      constructor() {
        this.bar = new Bar();
      }
    
      public runFoo(): string {
        return 'real foo : ' + this.bar.runBar();
      }
    }
    
    export default Foo;
    
    
    

    The test:

    import Foo from './Foo';
    import Bar from './Bar';
    
    jest.mock('./Bar');
    
    describe('Foo', () => {
      it('should return correct foo', () => {
        // As Bar is already mocked,
        // we just need to cast it to jest.Mock (for TypeScript) and mock whatever you want
        (Bar.prototype.runBar as jest.Mock).mockReturnValue('Mocked bar');
        const foo = new Foo();
        expect(foo.runFoo()).toBe('real foo : Mocked bar');
      });
    });
    
    
    

    See also jest.requireActual(moduleName)

提交回复
热议问题