I am swapping to Jest from Mocha, and I'm wondering if there is a way to spy on a React method. For example, let's say I have the following method in my component (ignore the sdk
library, it just constructs a jQuery Ajax call):
getData() { sdk.getJSON('/someURL').done(data => { this.setState({data}); }); }
Using Sinon I would test this by spying on the prototype like so:
it('should call getData', () => { sinon.spy(Component.prototype, 'getData'); mount(<Component />); expect(Component.prototype.getData.calledOnce).to.be.true; });
This would ensure code coverage without mocking the method. Is there similar functionality in Jest?
EDIT: Also, if this functionality doesn't exist, what is the next best strategy for testing API calls?
There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.
Another approach to mock a particular function from an imported module is to use the jest. spyOn function. The API for this function seems to be exactly what we need for our use case, as it accepts an entire module and the particular export that should be spied on.
unmock(moduleName) Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).
The jest. mock() method takes the module path as an argument and an optional implementation of the module as a factory parameter. For the factory parameter, we specify that our mock, axiosConfig , should return an object consisting of baseURL and request() . The baseUrl is set to the base URL of the API.
Actually you can use jest.spyOn jest.spyOn
If method is called when component created use:
import { mount } from 'enzyme'; describe('My component', () => { it('should call getData', () => { const spy = jest.spyOn(Component.prototype, 'getData'); mount(<Component />); expect(spy).toHaveBeenCalledTimes(1) }); })
or if you have it in your DOM and method use bind you can use:
import { shallow } from 'enzyme'; describe('My component', () => { it('should call getData', () => { const wrapper = shallow(<Component />); const instance = wrapper.instance() const spy = jest.spyOn(instance, 'getData'); wrapper.find('button').simulate('click') expect(spy).toHaveBeenCalledTimes(1) }); })
There is the spyOn
method, that was introduced with v19 some days ago, that does exactly what you are looking for
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