Using Jest and React, How do I spy one this.setState()
and test weather the function hasBeenCalled()
it('shall update targets when engine register has been called', () =>
{
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(wrapper.state.targets).toEqual({}); // pass
wrapper.engine.register(FIXTURE.REACT_REF); // pass
expect(wrapper.state.targets).not.toEqual({}); //pass
expect(wrapper.setState).toHaveBeenCalled(); // fail
});
Engine Getter:
get engine() {
return {
state: this.state,
register: target => {
this.setState(LazyloadUtils.registerOneTarget(target));
},
};
}
Testing the useState Hook with Enzyme import React from "react"; const App= () => { const [name, setName] = React. useState(""); return ( <form> <div className="row"> <div className="col-md-6"> <input type="text" placeholder="Enter your name" className="input" onChange={(e) => { setName(e.
To enable us to mock useState, we use React. useState (line #5) instead of using the usual named import (i.e. import { useState } from 'react'). Below is our Jest unit test for the component. Before rendering the component for testing, we create a constant 'setStateMock' and mock it with a jest function jest.
Ideally, you'd want to check for the key in state object that your setState method is updating
expect(wrapper.state('foo')).toEqual('bar')
IF you really want to spy on the method itself, you can mock the setState method on the component prototype. You would need to do this before creating a shallow copy of your component.
it('shall update targets when engine register has been called', () =>
{
LazyloadProvider.prototype.setState = jest.fn();
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(wrapper.setState).toHaveBeenCalled();
}
if you want to continue testing after the call to setState
, you should spy, not mock the method
it('shall update targets when engine register has been called', () =>
{
const setStateSpy = jest.spyOn(LazyloadProvider.prototype, 'setState');
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(setStateSpy).toHaveBeenCalled();
// write more tests that want the dom to update
}
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