【发布时间】:2019-01-02 01:04:46
【问题描述】:
我是 jest/enzyme 的新手,我尝试测试一个函数。该测试试图测试getData() 设置了状态中返回的数组。
这就是它的样子:
getData () {
axios.get('http://localhost:8080/targeting-data').then(response => {
this.setState({
targetingData: response.data,
load: true
})
})
}
componentDidMount () {
this.interval = setTimeout(() => {
this.getData()
}, 3000)
}
我的第一次测试:
import FormWrapper from './../containers/FormWrapper/FormWrapper'
const mockGetData = jest.spyOn(FormWrapper.prototype, 'getData')
it('testing', () => {
mockGetData()
expect(formWrapper.state().targetingData).toHaveLength(8)
})
我失败了:
expect(received).toHaveLength(length)
Expected value to have length:
8
Received:
[]
received.length:
0
我的第二个测试:
it('getDataFunc', (done) => {
mockGetData().then(res => {
expect(res).toHaveLength(8)
done()
})
})
我失败了:
TypeError: Cannot read property 'then' of undefined
(node:6302) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'setState' of undefined
(node:6302) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
我对如何测试它感到困惑,如果有任何建议,我都会很高兴。谢谢
【问题讨论】:
-
jestjs.io/docs/en/tutorial-async 这可能对你有帮助。
-
欢迎来到 Stack Overflow。有多种模拟远程 API 调用的选项,因此您无需修改代码即可对其进行测试
-
感谢您的建议@varit05。但我仍然对如何实现它感到困惑
-
嗨@Mikkel你能告诉我其中一个吗?
-
可能相同(或至少非常接近):stackoverflow.com/questions/51876091/…
标签: javascript reactjs unit-testing jestjs enzyme