上下文API单元测试因TypeError失败

时间:2019-01-26 07:56:37

标签: reactjs jestjs enzyme

我有一个HOC组件WithContext(在方便命名为withContext.js的文件中),如下所示

import React from 'react';
import { DEFAULT_STATE } from './store';
const MyContext = React.createContext(DEFAULT_STATE);


export function WithContext(Component) {
    return function WrapperComponent(props) {
        return (
            <MyContext.Consumer>
                {state => <Component {...props} context={state} />}
            </MyContext.Consumer>
        );
    };
};

和使用它的组件如下

import React from "react";
import { WithContext } from './withContext';

const MyComp = (context) => { 
    return (
        <div className="flex dir-col" id="MyComp">
            <p>This is a test</p>
        </div>
    )
};

export default WithContext(MyComp);

我还有一个单元测试,旨在测试此MyComp组件。单元测试遵循

import React from "react";
import {shallow} from "enzyme";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { WithContext } from './withContext';

// We need to configure our DOM 
import jsdom from 'jsdom'
const {JSDOM} = jsdom;
const {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView

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

beforeEach(() => {
    jest.resetModules()
})

//Takes the context data we want to test, or uses defaults
const getMyContext = (context = {
        state : {}
    }) => {

  // Will then mock the MyContext module being used in our MyComp component
  jest.doMock('withContext', () => {
    return {
      MyContext: {
        Consumer: (props) => props.children(context)
      }
    }
  });

  // We will need to re-require after calling jest.doMock.
  // return the updated MyComp module that now includes the mocked context
  return require('./MyComp').default;

};

describe("MyComp component loading check", () => {
    test("Renders the MyComp component correctly", () => {
        const MyCompContext = getMyContext();
        const wrapper = shallow(<MyComp/>);
        // make sure that we are able to find the header component
        expect(wrapper.find(".flex").hostNodes().length).toBe(1);
    });
});

但是此测试始终失败并显示消息

 TypeError: (0 , _withContext.WithContext) is not a function

      };
export default WithContext(MyComp);

您能告诉我这是怎么回事吗?

谢谢

1 个答案:

答案 0 :(得分:0)

看起来您正在使用withContext模拟jest.doMock,但是您从工厂函数返回的模拟不包含WithContext函数。

然后,当您require('./MyComp').defaultwithContext模块中使用MyComp模拟时,尝试export default WithContext(MyComp);时失败,因为withContext模拟没有定义一个WithContext函数。

相关问题