How to spy componentWillMount using jester and enzyme

I am trying to check if componentWillMount has been called, and for this my test

test('calls `componentWillMount` before rendering', () => { let fn = jest.fn(SomeComponent.prototype.componentWillMount) mount(<SomeComponent />) expect(fn).toHaveBeenCalled() }) 

But even when the componentWillMount method is called, the test fails. What am I missing here?

+6
source share
4 answers

I don’t know if other answers helped your question, but you don’t need to test the WillMount component. The reaction should already do this testing for you.

More appropriate for your testing would be to test the functions or actions that you put into this method for your component.

If you make an API call, run a props-based function, or something else, this is what you should test. Select the function / action / code that componentWillMount calls the triggers, and make statements and expectations about it.

Example:

component:

 class YourComponent extends Component { componentWillMount() { /*this fetch function is actually what you want to test*/ this.props.fetch('data') } render() { /* whatever your component renders*/ } } 

Tests:

 test('should call fetch when mounted', () => { let mockFetch = jest.fn() const wrapper = mount(<SomeComponent fetch={mockFetch}/>); expect(wrapper).toBeDefined(); expect(mockFetch).toHaveBeenCalled(); expect(mockFetch.mock.calls[0]).toEqual(['data']) }); 
+12
source

At first I would like to use spy for the componentWillMount componentWillMount , but also use .and.CallThrough() so as not to interfere with its contents. Hope this helps:

 it('should check that the componentWillMount method is getting called', () => { spyOn(SomeComponent.prototype, 'componentWillMount').and.callThrough(); const wrapper = mount(<SomeComponent />); expect(wrapper).toBeDefined(); expect(SomeComponent.prototype.componentWillMount).toHaveBeenCalledTimes(1); }); 
+2
source

Try the following:

 test('calls `componentWillMount` before rendering', () => { const onWillMount = jest.fn(); SomeComponent.prototype.componentWillMount = onWillMount; mount(<SomeComponent />); expect(onWillMount).toBeCalled(); }); 
0
source

I do not believe the above answer solves the problem. This joke allows you to use the method, but does not allow you to callThrough track the status of the call. The solution that works best for me is to configure the test using a component with componentWillMount . Based on a joke, we just complicate the situation.

 describe('componentWillMount', () => { const calls = [] class Component1 extends Components { componentWillMount() { calls.push(new Date) } render() { ... } } afterEach(() => calls.splice(0, calls.length)) it('has been called', () => { mount(<Component1 />) expect(calls.length).toBe(1) }) }) 
0
source

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


All Articles