timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
738 stars 39 forks source link

Bug with classes `this` keyword #97

Open a7medm7med opened 2 years ago

a7medm7med commented 2 years ago

Take a look at this code:

import { when } from 'jest-when';

class MyName {
    reGetName( name: string ) {
        return name;
    }

    getName( name: string ) {
        return this.reGetName( name );
    }
}

it( 'test my name', () => {
    const component = new MyName();
    jest.spyOn( component, 'getName' );

    when( component.getName )
        .calledWith( 'mark' )
        .mockReturnValue( 'mark' );

    expect( component.getName( 'mark' ) ).toBe( 'mark' ); // Ok
    expect( component.getName( 'john' ) ).toBe( 'john' ); // Error
} );

Once run this test it gives this error: TypeError: this.reGetName is not a function

The problem is jest-when change the default implementation of the function.

My temporary solution is reset the jest-when implementation by doing something like this:

it( 'test my name 2', () => {
    const component = new MyName();
    jest.spyOn( component, 'getName' );

    when( component.getName )
        .calledWith( 'mark' )
        .mockReturnValue( 'mark' )
        .defaultImplementation( MyName.prototype.getName.bind( component ) );

    expect( component.getName( 'john' ) ).toBe( 'john' ); // Ok
    expect( component.getName( 'mark' ) ).toBe( 'mark' ); // Ok
} );

To solve this issue jest-when should not change the function's implementation if it's not called with the added arguments.

3y3 commented 2 years ago

Should be fixed by https://github.com/timkindberg/jest-when/pull/98