Created
February 4, 2019 21:56
-
-
Save mlg87/51f970054ac02b2b2045864bdef6c003 to your computer and use it in GitHub Desktop.
mock a static class method in jest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./SomeClass.ts | |
export default class SomeClass { | |
public static myMethod(params: any) { | |
... do something | |
} | |
} | |
// ./SomeComponent.tsx | |
export default class SomeComponent extends React.Component { | |
public render() { | |
<input onChange={e => this.handleChange(e)} ... /> | |
} | |
private handleChange(e) { | |
SomeClass.myMethod(e) | |
} | |
} | |
// ./SomeComponent.test.tsx | |
const myMethodMock = jest.fn() | |
jest.mock('./SomeClass', () => ({ | |
default: class { | |
public static myMethod(params) { | |
myMethodMock(params) | |
} | |
} | |
}) | |
) | |
it('calls SomeClass.myMethod with the params', () => { | |
const testParams = { whatever: 'hi' } | |
const wrapper = mount(<SomeComponent />) | |
const input = wrapper.find('input') | |
input.simulate('change', testParams) | |
expect(myMethodMock).toHaveBeenCalledWith(testParams) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment