jest-when icon indicating copy to clipboard operation
jest-when copied to clipboard

Bug with classes `this` keyword

Open a7medm7med opened this issue 1 year ago • 1 comments

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.

a7medm7med avatar Jul 31 '22 07:07 a7medm7med

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

3y3 avatar Oct 22 '22 13:10 3y3