So I have a Classical component in React, RecipesNew, that has the following initial state:
this.state = {
recipe: {
title: '',
description: '',
prepTime: '',
cookingTime: ''
},
errors: false
}
It has a form and the following method for onSubmit:
handleOnSubmit = (e) => {
e.preventDefault()
this.props.startAddRecipe(recipe)
.then(recipe => this.props.history.push(`/recipes/${recipe._id}`))
.catch(err => this.setState({ errors: err }))
}
The startAddRecipe method on props rerturns a promise which resolves when an axios call within it, to my db, resolves and then dispathces an action to update the redux state. The promise rejects when the axios call within it rejects.
I want to test startAddRecipe for when the startAddRecipe rejects and sets this.state.errors.
Within my tests file I have wrttien a function that returns a promise and rejects straight away to pass to RecipesNew as the startAddRecipe prop:
const startAddRecipeRejectsSpy = jest.fn((recipeData = {}) => {
return Promise.reject(['Test Error', 'Test Error 2'])
})
This is my test to test when the Promise rejects. I assumed the state.errors would be populated with this array : ['Test Error', 'Test Error 2']
test('startAddRecipe rejects correctly', () => {
const wrapper = shallow(<RecipesNew startAddRecipe={startAddRecipeRejectsSpy} />);
const mockRecipe = {
title: 'Test Title',
description: 'Test Description',
prepTime: 10,
cookingTime: 10
}
wrapper.setState({ recipe: mockRecipe })
wrapper.find('form').simulate('submit',{ preventDefault: () => { } })
expect(startAddRecipeRejectsSpy).toHaveBeenLastCalledWith(mockRecipe)
expect(startAddRecipeRejectsSpy(mockRecipe)).rejects.toEqual(['Test Error', 'Test Error 2'])
expect(wrapper.update().state().errors).toBe(['Test Error', 'Test Error 2']);
expect(wrapper.update()).toMatchSnapshot();
})
Everything works apart from the last 2.
The second to last says:
Expected: ["Test Error", "Test Error 2"]
Received: false
So basically the state appears to not be changing?
Finally the snap shot in the last one is not what I expected as when this.state.errors
is not falsey I map over the array of errors and produce a list - this list does not appear in snaphot.
Any ideas? Ive read lots of threads on this but nothing seems to match my issue.
Any help appreciated.
Thanks!