[英]Best way to write integration tests in React with Redux and Enzyme
I'm trying to write some integrations tests in my application.我正在尝试在我的应用程序中编写一些集成测试。
I have a couple API calls, that's called on componentDidMount and on button click.我有几个 API 调用,在 componentDidMount 和按钮单击上调用。 The API response it's saved on Store, which update the view.
API 响应它保存在 Store 中,从而更新视图。
How can I test this integration with the API?如何测试与 API 的集成?
This is my WIP code:这是我的 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?
})
Thanks in advance.提前致谢。
There are few gotchas there:那里有几个陷阱:
redux-mock-store
does not run reducer. redux-mock-store
不运行reducer。 To test real reducer and real actions(otherwise your axios
's mock will never be applied to component) you need using real store instead.axios
的模拟将永远不会应用于组件),您需要使用真正的商店。axios
mocks are Promise-based you need either moxios.wait
or setTimeout()
/ await <anything>
before running check.axios
是基于 Promise 的,因此您需要moxios.wait
或setTimeout()
/ await <anything>
在运行检查之前。 Otherwise Promise will not be fullfilled by time you try to validate something.wrapper.update()
since it will run by redux once you handle items #1 and #2wrapper.update()
,因为一旦您处理了项目 #1 和 #2,它将由 redux 运行In your test you have to verify your component looks like expected after data is loaded successfully.在您的测试中,您必须在成功加载数据后验证您的组件是否符合预期。
// 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.