【发布时间】:2018-06-11 13:10:00
【问题描述】:
我刚刚写完我的第一个Reactjs 组件,我准备写一些测试(我使用了material-ui 的Table 和Toggle)。
我读到了jest 和enzyme,但我觉得我仍然缺少一些东西。
我的组件看起来像这样(简化):
export default class MyComponent extends Component {
constructor() {
super()
this.state = {
data: []
}
// bind methods to this
}
componentDidMount() {
this.initializeData()
}
initializeData() {
// fetch data from server and setStates
}
foo() {
// manuipulatig data
}
render() {
reutrn (
<Toggle
id="my-toggle"
...
onToggle={this.foo}
>
</Toggle>
<MyTable
id="my-table"
data={this.state.data}
...
>
</MyTable>
)
}
}
现在开始测试。我想为以下场景编写一个测试:
- 使用模拟数据馈送 initializeData。
- 切换我的切换
- 断言数据已更改(我应该断言数据本身还是断言 my-table 更好?)
所以我从一开始就是:
describe('myTestCase', () => {
it('myFirstTest', () => {
const wrapper = shallow(<MyComponent/>);
}
})
我运行了它,但它失败了:ReferenceError: fetch is not defined
我的第一个问题是,我如何模拟 initializeData 以克服调用使用 fetch 的真实代码的需要?
我遵循了这个答案:https://stackoverflow.com/a/48082419/2022010 并想出了以下内容:
describe('myTestCase', () => {
it('myFirstTest', () => {
const spy = jest.spyOn(MyComponent.prototype, 'initializeData'
const wrapper = mount(<MyComponent/>);
}
})
但我仍然遇到同样的错误(我也尝试使用componentDidMount 而不是initializeData,但结果相同)。
更新:我错了。我确实收到了一个 fetch is not defined 错误,但这次它来自 Table 组件(它是 material-ui 的 Table 的包装)。现在我想起来了,我确实有很多“获取”的过程......我想知道如何照顾它们。
【问题讨论】:
-
也许先尝试搜索答案 - Jest 文档非常好facebook.github.io/jest/docs/en/mock-functions.html
-
@DarrenSweeney 我尝试了这种方法:stackoverflow.com/a/48082419/2022010 但我仍然得到相同的
fetch is not difined错误:( -
或许你可以试试React Testing(代替enzyme)
-
我会使用 node-fetch 在 jest 环境中定义 fetch 并使用 nock 拦截网络调用。使 node-fetch 全局可用,并为您的测试定义服务器为特定调用返回的内容。
标签: javascript reactjs jestjs enzyme