M
M
Mariik2019-04-30 22:42:01
React
Mariik, 2019-04-30 22:42:01

How to track a method call in a component in Enzyme?

Hi
There is such a simple component:

import React, {Component} from 'react';
import axios from 'axios';

export class Posts extends Component {
    
    state = {
        posts: null,
        loading: false
    }

    componentDidMount() {}

    loadPosts = () => {
        this.setState({loading: true}, () => {
            axios.get('https://jsonplaceholder.typicode.com/todos')
            .then( d => this.setState({
                posts: d.data
            }));    
        });
    }

    render() {
        return (<div>
                <h4>I am posts</h4>
                <button onClick= {this.loadPosts}>Load posts</button>
            </div>);
    }
    
}

Now I want to test that when the button is pressed, the method of the Posts.loadPosts component is called.
Here is the code of my test:
import React from 'react';
import { configure, mount} from 'enzyme';
import { expect } from 'chai';
import Adapter from 'enzyme-adapter-react-16';
import { Posts } from '../Components/Posts';
import sinon from 'sinon';
configure({ adapter: new Adapter() });

describe('Posts', () => {

    let wrapper;
    let inst;

    beforeEach(() => {
        wrapper = mount(<Posts />);
        inst = wrapper.instance();
        sinon.spy(inst, 'loadPosts');
        wrapper.find('button').simulate('click');
    });

    it('should load posts on button click', () => {
        wrapper.update();
        expect(inst.loadPosts).to.have.property('callCount', 1);
    });

    it('should set `loading` to true', () => {
        expect(wrapper.state('loading')).to.equal(true);
    });
});

But here's the problem - the test fails:
Exception error:  expected [Function] to have property 'callCount' of 1 but got 0

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question