gpt4 book ai didi

javascript - 使用 Redux 和 Enzyme 在 React 中编写集成测试的最佳方法

转载 作者:行者123 更新时间:2023-12-02 22:42:13 25 4
gpt4 key购买 nike

我正在尝试在我的应用程序中编写一些集成测试。

我有几个 API 调用,它们是在 componentDidMount 和按钮单击时调用的。 API 响应保存在 Store 上,从而更新 View 。

如何测试与 API 的集成?

这是我的 WIP 代码:

    let wrapped

const options = {
disableLifecycleMethods: true
}

const mockPlanet = {
name: "Yavin IV",
climate: "temperate, tropical",
terrain: "jungle, rainforests",
population: "1000",
films: ["A New Hope"],
url: "https://swapi.co/api/planets/3/"
}

const initialPlanet = {
name: "Alderaan",
climate: "temperate",
terrain: "grasslands, mountains",
population: "2000000000",
films: ["A New Hope", "Revenge of the Sith"],
url: "https://swapi.co/api/planets/2/"
}

const mockStore = configureMockStore([thunk])

const store = mockStore({
planets:{
planetCount: 1,
activePlanet: initialPlanet,
planetCache: [],
loading: false,
error: null
}
})

const address = /https:\/\/swapi.co\/api\/planets/[0-9]/

beforeEach(()=>{
moxios.install()
moxios.stubRequest(
address,
{
status: 200,
response: mockPlanet
}
)
})

afterEach(()=>{
moxios.uninstall()
})

it('Fetch planet on click',()=>{

wrapped = mount(
<Provider store={store}>
<App/>
</Provider>, options
)

wrapped.find('.button-get-planet').first().simulate('click')
wrapped.update()

// What should I test here?
})

提前致谢。

最佳答案

那里有一些陷阱:

  1. redux-mock-store does not run reducer 。要测试真实的 reducer 和真实的操作(否则你的 axios 的模拟将永远不会应用于组件),你需要使用真实的存储。
  2. 自从你的axios模拟是基于 Promise 的,您需要 moxios.waitsetTimeout()/await <anything>在运行检查之前。否则,当您尝试验证某些内容时,Promise 将无法实现。
  3. 而你实际上并不需要wrapper.update()因为一旦你处理了#1 和#2 项,它就会由 redux 运行

在测试中,您必须验证您的组件在数据成功加载后是否符合预期。

// simulate click
// check some "Loader" is displayed if expected
await Promise.resolve(); // just to flush microtasks queue - or use moxios.wait()
// check real data is rendered accordingly

关于javascript - 使用 Redux 和 Enzyme 在 React 中编写集成测试的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58547911/

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