I can't seem to figure this out. I am using the create-react-app and it is built into the test runner Jest. For all synchronous code, this works very well, but when promises are taunted, I can't get it to work.
The react component has a form in which I can simulate submit.
Recover component code fragments.
import {auth} from '../../lib/API_V2'
handleSubmit = (event) => {
console.log('submit')
event.preventDefault()
this.setState(prevState => ({
...prevState,
loading: true
}))
console.log('stateSet')
auth(this.state.userName, this.state.password)
.then(results => {
console.log('then')
this.setState(prevState => ({
...prevState,
loading: false
}))
this.props.afterAuth()
})
.catch(() => {
this.setState(prevState => ({
...prevState,
loading: false
}))
this.props.afterAuth()
})
}
Test code
jest.mock('../../lib/API_V2')
it.only(`should mock a login`, () => {
const myMock = jest.fn()
const authComp = mount(<AuthComponent afterAuth={myMock}/>)
authComp.find('.userName').simulate('change', {target: {value: 'userName'}})
authComp.find('.password').simulate('change', {target: {value: 'password'}})
expect(authComp.state().userName).toEqual('userName')
expect(authComp.state().password).toEqual('password')
authComp.find('[type="submit"]').get(0).click()
expect(myMock.mock.calls.length).toBe(1)
})
The lib API returns a promise. Instead, I have __mocks__/API_V2.jsnext to him. It looks like
function auth (lastname, accountNumber) {
console.log('yay!?')
return new Promise((resolve) => {
resolve({
accountNumber,
lastName: lastname
})
})
}
My test code never runs. If I register the mock function, I getfunction auth() {return mockConstructor.apply(this,arguments);}
https://facebook.imtqy.com/jest/docs/tutorial-async.html, , . . auth() undefined.
- ?
- -
src
Components
AuthComponent
AuthComponent.js
AuthComponent.test.js
index.js
Lib
API_V2
API_V2.js
index.js
__mocks__
API_V2.js