I'm trying to test if an event has been added in the init method called by componentDidMount, but that event is going to be added only if a component's attribute is set in "true" so I want to spy on the addEventHandler method and call the "toBeCalledWith('eventName')" so I have something like this:
export interface IMyComponentProps{
flag?: boolean;
}
export class MyComponent extends Component<IMyComponentProps> {
private myProperty: HTMLElement;
public componentDidMount() {
this.init();
}
private init() {
if (this.props.flag) {
this.myProperty.addEventListener("event", arg2, arg3);
}
}
}
Then I have my test looking like this:
test("Test 1", () => {
const spyInit = jest.spyOn(MyComponent.prototype, "init");
wrapper = mount(
<MyComponent />
);
expect(spyInit).toBeCalled();
})
but the test above does not cover if the addEventListener is called or not so I'm trying different ways like following, without success:
const spyAddListener = jest.spyOn(MyComponent.prototype, "myProperty.addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.instance().myProperty, "addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.prototype.myProperty, "addEventHandler");
any suggestion?
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest. fn() . If no implementation is given, the mock function will return undefined when invoked.
Jest's spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand. While writing unit tests you only test one particular unit of code, generally a function.
Not exactly answering the question, but people who are migrating from jasmine to jest may find this useful.
jest.spyOn(component, 'propertyName', 'get').mockReturnValue(...);
This is an equivalent to jasmine's spyOnProperty
:
jasmine.spyOnProperty(component, 'propertyName').and.returnValue(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With