I am trying to test the method call "fetchData" called in componentDidMount. I am using a High order component and have changed what needs to be changed but I don't know if that's everything, I have used export class ..., export default connect(...) and import {component} from './component' when calling it in the component.test.js
I can't find a solution to test the method was called when componentDidMount was called.
export class TestBase extends Component {
constructor(props){
super(props)
...
}
}
....
....
componentDidMount(){
this.fetchData();
}
fetchData = () =>{
const URLtemplate = '/api/users/getUserScore?email=';
const userEmail = this.props.auth.user.email;
var userURL = URLtemplate.concat(userEmail);
//console.log(userURL);
fetch(userURL)
.then(response => response.json())
.then(contacts => {console.log(contacts);
this.setState({
storeOne: contacts
}, () => {
console.log(this.state.storeOne)
});
})
.catch(error => console.log('parsing failing', error))
// debugger;
}
render() {
....
....
}
TestBase.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
getTheScores: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
})
export default connect(
mapStateToProps,
{ getTheScores, logoutUser }
)(TestBase);
My TestBase.test.js looks like this
import React from "react";
import { shallow } from "enzyme";
import {TestBase} from "./TestBase";
import { mount } from "enzyme";
describe("MyComponent", () => {
const auth = {
isAuthenticated: true,
user: {
id: "5ca0801291e0d7b175ea9ac5",
name: "Aaron Chatrath",
email: "testingabc@test.com"
},
loading: false
};
it("fetch to be called on componentDidMount", () => {
const wrapper = shallow(<TestBase auth={auth} logoutUser={jest.fn()} getTheScores={jest.fn()} />);
const instance = wrapper.instance(); // you assign your instance of the wrapper
jest.spyOn(instance, "fetchData"); // You spy on the fetchData
instance.componentDidMount();
expect(instance.fetchData).toHaveBeenCalledTimes();
});
});
Here, it doesn't seem to be work and I am getting the error of
expect(received)[.not].toHaveBeenCalledTimes(expected)
Expected value must be a number.
Got: undefined
I am sure there is a fix for this but I am just coming to grips with jest and enzyme. If a solution to this can be found, I'd be grateful. I tried using mount but then it asks for the store and to be used to wrap it but I am only trying to test a single method call from componentDidMount.
Aucun commentaire:
Enregistrer un commentaire