使用Jest渲染无效元素测试箭头功能组件

时间:2019-07-25 16:48:34

标签: react-native jestjs enzyme

在玩笑测试中尝试浅装(酶/玩笑)一个简单的React-Native按钮组件时收到以下错误。 从技术上讲,该测试通过了,但抛出了console.error

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

HeaderBackButton.js

import React from "react";
import { HeaderBackButton as HeaderBack } from "react-navigation";
import { Platform } from "react-native";

export const HeaderBackButton = (props) => {
    let { action } = props;
    return (
        <HeaderBack
            onPress={action}
            title={Platform.OS === "ios" ? "Back" : null}
            backTitleVisible={true}
            tintColor="#FFFFFF"
        />
    );
};

export default HeaderBackButton;

HeaderBackButton.test.js

import 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import { HeaderBackButton } from "../../src/components/HeaderBackButton";

import renderer from 'react-test-renderer';

const createTestProps = (props) => ({
    action: jest.fn(),
    ...props
});

const props = createTestProps({})

describe('HeaderBackButton', () => {
    test('HeaderBackButton matches shallow snapshot', () => {
        const rendered = shallow(<HeaderBackButton {...props} />);
        console.log(rendered.debug());
        expect(rendered).toMatchSnapshot();
    });
});

通常,这意味着我使用了不正确的默认/命名导出,但是此模式适用于所有其他组件,并且同时使用了命名和默认导出。唯一的区别是,在HeaderBackButton.js中,它具有重命名的导入,它也是命名导出的名称。另外,使用 expect(rendered.dive()).toMatchSnapshot(); 我通常会使用它,导致测试失败并显示此错误。

TypeError: ShallowWrapper::dive() can only be called on components

      17 |         const rendered = shallow(<HeaderBackButton {...props} />);
      18 |         console.log(rendered.debug())
    > 19 |         expect(rendered.dive()).toMatchSnapshot();
         |                         ^
      20 |         // expect(rendered).toMatchSnapshot();
      21 |     });
      22 | });

调试显示了通用组件

<Component 
  onPress={[Function: mockConstructor]} 
  title="Back" 
  backTitleVisible={true} 
  tintColor="#FFFFFF" 
/>

我希望它应该挂载并拍摄快照,而不会引发任何错误。

0 个答案:

没有答案