首页 文章

测试过程中的不变违规错误会消耗来自上下文api的prop的组件

提问于
浏览
0

我是jest和酶的新手,在测试反应组件时会遇到一些Invariant Violation错误,该组件消耗来自react的context API的prop . 我熟悉Invariant Violation错误及其可能的原因,但是,在这种情况下,我被困住了 . 一些建议非常感谢 . 这是一个最小的代码设置,仅用于演示目的 . 我在跑步
"enzyme":"3.7.0","enzyme-adapter-react-16":"1.6.0",
"jest":"23.6.0" .

注意,下面的代码工作正常,但是,只有在我尝试测试MyComponent.jsx时才会出现问题 .

index.jsx

import * as React from 'react';
import ReactDOM from 'react-dom';
import MyComponentWithContext from "./MyComponent";

const testValue = 'test value';

export const MyContext = React.createContext(testValue);

const App = () => {
    return (
        <div>
            <MyComponentWithContext/>
        </div>
    )
}

ReactDOM.render(
    <MyContext.Provider value={testValue}>
        <App/>
    </MyContext.Provider>,
    document.getElementById('root') || document.createElement('div')
)

MyComponent.jsx

import * as React from 'react';
import {MyContext} from './';

export class MyComponent extends React.Component {
    constructor(props) {
        super(props)
    }
    getContextValue() {
        return this.props.testValue
    }
    render() {
        return <div>{this.getContextValue()}</div>;
    }
}

const MyComponentWithContext = () => (
    <MyContext.Consumer>
        {testValue => <MyComponent testValue={testValue}/>}
    </MyContext.Consumer>
)

export default MyComponentWithContext;

当我尝试像这样测试MyComponent时:

MyComponent.unit.test.js

import React from 'react';
import {shallow} from 'enzyme';
import {MyComponent} from '../MyComponent';

describe('<MyComponent />', () => {
    const testValue = 'test value';
    it('should return test value', () => {
        const wrapper = shallow(<MyComponent testValue={testValue}/>);
        expect(wrapper.instance().getContextValue()).toEqual(testValue);
    });

});

这给了我以下错误:

不变违规:元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:undefined . 您可能忘记从其定义的文件中导出组件,或者您可能混淆了默认导入和命名导入 . 检查 App 的render方法 .

| ReactDOM.render(
         |          ^
      18 |     <MyContext.Provider value={testValue}>
      19 |         <App/>
      20 |     </MyContext.Provider>,

1 回答

  • 0

    不应在单元测试中评估 ReactDOM.render(...) . 模块组织不当 . index.js提供了在单元测试中应避免的副作用,它还具有可避免的MyComponent.js的不必要的循环依赖 .

    export const MyContext = React.createContext(testValue);
    

    应该移动到单独的模块,因此组件模块可以直接导入它 .

相关问题