【发布时间】:2017-07-04 17:31:55
【问题描述】:
我似乎无法弄清楚这一点。我正在使用 create-react-app,它内置在测试运行程序 Jest 中。对于所有同步代码,它似乎工作得很好,但是在模拟承诺时,我似乎无法让它工作。
一个反应组件有一个我可以模拟提交的表单。
React 组件代码 sn-ps。
//Top of the page
import {auth} from '../../lib/API_V2'
// ... //
// Handle submit runs when the form is submitted
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 => {
// NEVER RUNS
console.log('then')
// stuff omitted
this.setState(prevState => ({
...prevState,
loading: false
}))
this.props.afterAuth()
})
.catch(() => {
// also never runs
// omitted
this.setState(prevState => ({
...prevState,
loading: false
}))
this.props.afterAuth()
})
}
测试代码
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) // FAILS
})
API 库返回一个承诺。我没有使用它,而是在它旁边有一个__mocks__/API_V2.js。看起来像这样
function auth (lastname, accountNumber) {
console.log('yay!?')
return new Promise((resolve) => {
resolve({
accountNumber,
lastName: lastname
})
})
}
我的模拟测试代码似乎从未运行过。如果我记录模拟函数,我会得到function auth() {return mockConstructor.apply(this,arguments);}
我已尝试按照说明进行操作 https://facebook.github.io/jest/docs/tutorial-async.html,但似乎没有调用我的模拟方法。实际的方法也不是。相反,我对auth() 的调用返回未定义。
有人有什么想法吗?
-- 补充信息--
src
Components
AuthComponent
AuthComponent.js
AuthComponent.test.js
index.js
Lib
API_V2
API_V2.js
index.js
__mocks__
API_V2.js
【问题讨论】:
-
我最终手动模拟了它,而不是使用 mocks 目录。 jest.mock('../../lib/API_V2, () => {auth: function ...})
标签: javascript reactjs jestjs create-react-app