Answer the question
In order to leave comments, you need to log in
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>);
}
}
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);
});
});
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 questionAsk a Question
731 491 924 answers to any question