我似乎无法弄清楚这一点。我正在使用create-react-app,它内置在测试运行程序Jest中。对于所有同步代码而言,它似乎都可以很好地工作,但是当模拟承诺时,我似乎无法使其正常工作。
react组件具有一种我可以模拟提交的形式。
反应组件代码片段。
//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库返回一个Promise。我没有使用它,而是使用__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
我认为您正在遇到与此问题相关的错误:https : //github.com/facebook/jest/issues/2070
由于您实际上是在尝试导入名为的文件API_V2/index.js
,因此需要进行模拟index.js
。但是,这样做会非常麻烦,因为它对于您尝试模拟的每个index.js文件都是有效的模拟。
目前最好的方法是重写某些代码以使用依赖注入,并将模拟传递给需要使用的任何东西 { auth }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句