我正在尝试在我的应用程序中编写一些集成测试。
我有几个 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?
})
提前致谢。
最佳答案
那里有一些陷阱:
-
redux-mock-store
does not run reducer 。要测试真实的 reducer 和真实的操作(否则你的axios
的模拟将永远不会应用于组件),你需要使用真实的存储。 - 自从你的
axios
模拟是基于 Promise 的,您需要moxios.wait
或setTimeout()
/await <anything>
在运行检查之前。否则,当您尝试验证某些内容时,Promise 将无法实现。 - 而你实际上并不需要
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/