gpt4 book ai didi

javascript - 为我的第一个组件写一个 Jest 测试

转载 作者:行者123 更新时间:2023-11-29 20:53:07 25 4
gpt4 key购买 nike

我刚刚完成了我的第一个 Reactjs 组件的编写,我准备编写一些测试(我使用了 material-uiTable切换)。我阅读了有关 jestenzyme 的内容,但我觉得我仍然缺少一些东西。

我的组件看起来像这样(简化):

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>
)
}
}

现在进行测试。我想为以下场景编写测试:

  1. 为 initializeData 提供模拟数据。
  2. 切换我的切换
  3. 断言数据已更改(我应该断言数据本身还是断言我的表更好?)

所以我从一开始就开始:

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 的包装)。现在回想起来,一路上确实有很多“牵绊”……我想知道如何处理它们。

最佳答案

浏览器支持

fetch,但 jest/enzyme 在 Node 环境中运行,因此 fetch 不是测试代码中的全局可用函数。有几种方法可以解决这个问题:

1:全局模拟 fetch - 这可能是最简单的解决方案,但可能不是最干净的。

global.fetch = jest.fn().mockResolvedValue({
json: () => /*Fake test data*/
// or mock a response with `.text()` etc if that's what
// your initializeData function uses
});

2:将您的 fetch 调用抽象到服务层并将其作为依赖项注入(inject) - 这将使您的代码更加灵活(尽管更多样板文件),因为您可以将 fetch 实现隐藏在您选择的任何接口(interface)后面。然后在未来的任何时候,如果您决定使用不同的获取库,您可以换掉服务层中的实现。

// fetchService.js
export const fetchData = (url) => {
// Simplified example, only takes 'url', doesn't
// handle errors or other params.
return fetch(url).then(res => res.json());
}

// MyComponent.js
import {fetchService} from './fetchService.js'

class MyComponent extends React.Component {
static defaultProps = {
// Pass in the imported fetchService by default. This
// way you won't have to pass it in manually in production
// but you have the option to pass it in for your tests
fetchService
}
...
initializeData() {
// Use the fetchService from props
this.props.fetchService.fetchData('some/url').then(data => {
this.setState({ data });
})
}
}

// MyComponent.jest.js
it('myFirstTest', () => {
const fetchData = jest.fn().mockResolvedValue(/*Fake test data*/);
const fetchService = { fetchData };
const wrapper = mount(<MyComponent fetchService={fetchService} />);
return Promise.resolve().then(() = {
// The mock fetch will be resolved by this point, so you can make
// expectations about your component post-initialization here
})
}

关于javascript - 为我的第一个组件写一个 Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50798535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com