I'm trying to test a function in React using Jest. It's working in production and development environments perfectly but Jest is saying it doesn't called. As a consequence the state in test returns 0 data length while it should be 1!
This is the function:
addStory(story) {
const idToken = this.state.user.idToken
if (!idToken) return
const storyProps = {
Title: story.title,
Body: story.body,
UserEntityKey: story.userEntityKey,
AuthorName: this.state.user.displayName,
AuthorPicture: this.state.user.photoURL
}
// Axios call should return Promise result for proper testing.
const promise = Axios.post(apiUrl, storyProps, { headers: { 'Authorization': idToken } })
promise.then(res => res.data)
promise.then(newStory => {
newStory.data.AuthorName = this.state.user.displayName
newStory.data.AuthorPicture = this.state.user.photoURL
this.setState(({ data }) => {
data.unshift(newStory.data)
return { data: data, isAddStoryVisible: false }
})
})
promise.catch((error) => {
console.error(error)
})
return promise
};
and this is the test:
test('Story adds based on mocked backend response', async () => {
MockAxios.post.mockImplementationOnce(() =>
Promise.resolve(story)
)
const storyApp = shallow(<StoryApp />);
// Test without idToken
// Axios call should return Promise result.
await storyApp.instance().addStory(story)
expect(storyApp.state().data.length).toEqual(0)
storyApp.setState((prev) => {
prev.user = {
idToken: "asdf",
displayName: "Test name",
photoURL: "Test photo"
}
return prev
})
// Test with idToken
await storyApp.instance().addStory(story)
expect(storyApp.state().data.length).toEqual(1)
})
and finally here is the test output:
● Story adds based on mocked backend response
expect(received).toEqual(expected)
Expected value to equal:
1
Received:
0
92 | // Test with idToken
93 | await storyApp.instance().addStory(story)
> 94 | expect(storyApp.state().data.length).toEqual(1)
| ^
95 | })
96 |
97 | test('Story deletes based on mocked backend response', async () => {
at Object.toEqual (__tests__/App.test.js:94:40)
at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
at asyncGeneratorStep (__tests__/App.test.js:25:103)
at _next (__tests__/App.test.js:27:194)
Thank you :-)
Aucun commentaire:
Enregistrer un commentaire