Jest Functional Spy

I'm moving over to joke with mocha, and I wonder if there is a way to spy on the response 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 sine, I would check this by spying on a prototype, for example:

  it('should call getData', () => { sinon.spy(Component.prototype, 'getData'); mount(<Component />); expect(Component.prototype.getData.calledOnce).to.be.true; }); 

this would ensure that the code is not mocked by this method. Is there any similar functionality as a joke?

EDIT: Also, if this function does not exist, what is the next best strategy for testing API calls?

+22
source share
4 answers

There is a spyOn method that was introduced with v19 a few days ago that does exactly what you are looking for

+15
source

You can actually use jest.spyOn jest.spyOn

If the method is called when the component is created, use:

 import { mount } from 'enzyme'; describe('My component', () => { it('should call getData', () => { const spy = jest.spyOn(Component.prototype, 'getData'); mount(<Component />); expect(Component.prototype.getData).toHaveBeenCalledTimes(1) }); }) 

or if you have this in your DOM and bind method , 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) }); }) 
+18
source

You can move on to the new spyOn method, and the following should work fine.

 it('should call getData', () => { Component.prototype.getData = jest.fn(Component.prototype.getData); expect(Component.prototype.getData).toBeCalled(); }); 
+4
source

I am using Jest with React 16.8 - this worked for me:

  it("lifecycle method should have been called", () => { jest.spyOn(RedirectingOverlay.prototype, 'componentWillUnmount'); jest.spyOn(RedirectingOverlay.prototype, 'componentDidMount'); const wrapper = mount(<RedirectingOverlay message="Hi There!"/>); expect(RedirectingOverlay.prototype.componentDidMount).toHaveBeenCalledTimes(1) wrapper.unmount() expect(RedirectingOverlay.prototype.componentWillUnmount).toHaveBeenCalledTimes(1) }) 

Also using:

  • "enzyme": "^3.6.0"
  • "jest": "23.5.0"
  • "enzyme-adapter-react-16": "^1.5.0"
0
source

Source: https://habr.com/ru/post/1264662/


All Articles