jest-when
jest-when copied to clipboard
Bug with classes `this` keyword
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.
Should be fixed by https://github.com/timkindberg/jest-when/pull/98