如何在React中使用Enzyme测试带有钩子的HOC?

时间:2020-09-12 11:12:11

标签: reactjs react-hooks enzyme

我已经实现了使用Context Provider包装组件的HOC:

import React, { useState } from "react"
import Context from "./context"

const WithProvider = Component => {
    const WithContext = props => {
        const [visible, setVisible] = useState(true); // This invokes an issue in the test
        const type = props.type || "info";
        const darkmode = props.darkmode;
        const value = { type, visible, setVisible, darkmode };

        return (visible && <Context.Provider value={value} >
            <Component {...props} />
        </Context.Provider>);
    }
    return WithContext
}

export default WithProvider

此HOC的单元测试为:

import React from "react"
import renderer from "react-test-renderer"
import Enzyme, { shallow, mount } from "enzyme"
import Adapter from "enzyme-adapter-react-16"
import withProvider from "./index"
import Context from "./context"

Enzyme.configure({ adapter: new Adapter() })

describe("withProvider High Order Component", () => {

    it("should return a component with context provider", () => {
        const Component = () => <button>Notify</button>
        const ComponentProvider = withProvider(<Component />) // The issue is here
        expect(ComponentProvider).find(<Context.Provider >
            <Component />
        </Context.Provider>)
    });
})

由于useState钩子,该测试失败。

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
 

我不知道在测试中调用Hook的方式。

如何通过Hook重构测试以使其适合?

0 个答案:

没有答案