Reputation: 17352
How do I mock a nested console.error
in a jest unit test?
With my attempt (see below) I do get the error jest.fn() value must be a mock function or spy. Received: undefined
Function
_onSubmit = (event) => {
event.preventDefault()
const { username, password } = this.state
return this.props.createUserMutation({
variables: { username, password }
}).then(response => {
const token = response.data.createUser.token
if (token) {
// do something
} else {
console.error('No token recieved')
}
})
}
Test
it('_onSubmit() should log error, if no token is recieved', (done) => {
console['error'] = jest.fn()
const createUserMutation = () => {
return Promise.resolve({
data: {
createUser: { token: undefined }
}
})
}
const wrapper = shallow(<CreateAccount
createUserMutation={createUserMutation}
/>)
wrapper
.update()
.find(Form)
.props()
.onSubmit({ preventDefault: () => {} })
.then(() => {
expect(console.error()).toHaveBeenCalledWith('No token recieved')
done()
})
})
Upvotes: 0
Views: 1086
Reputation: 698
In this line, you're calling the function console.error
instead of passing the function to expect, that's why you get undefined, since this fn won't return anything:
expect(console.error()).toHaveBeenCalledWith('No token recieved')
Instead of the result, you want to pass the function itself like so:
expect(console.error).toHaveBeenCalledWith('No token recieved')
Also, since you're trying to mock the global console function, you'll probably have to change your mock setup to something along the lines of:
global.console.error = jest.fn()
Upvotes: 1