繁体   English   中英

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

[英]Best way to write integration tests in React with Redux and Enzyme

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

我有几个 API 调用,在 componentDidMount 和按钮单击上调用。 API 响应它保存在 Store 中,从而更新视图。

如何测试与 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不运行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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM