Material UI + 酶测试组件

IT技术 reactjs jestjs material-ui enzyme
2021-05-11 13:42:09

我在 React 中有一个组件,我试图用 Jest 测试它,不幸的是测试没有通过。

组件代码:

import React, {Component} from 'react';
import ProductItem from '../ProductItem/ProductItem';
import AppBar from "@material-ui/core/es/AppBar/AppBar";
import Tabs from "@material-ui/core/es/Tabs/Tabs";
import Tab from "@material-ui/core/es/Tab/Tab";
import {connect} from 'react-redux';


class ProductsTabsWidget extends Component {

    state = {
        value: 0
    }

    renderTabs = () => {
        return this.props.tabs.map((item, index) => {
            return item.products.length > 0 ? (<Tab key={index} label={item.title}/>) : false;
        })
    }

    handleChange = (event, value) => {
        this.setState({value});
    };


    renderConentActiveTab = () => {
        if (this.props.tabs[this.state.value]) {
            return this.props.tabs[this.state.value].products.map((productIndex) => {
                return (<ProductItem key={productIndex} {...this.props.products[productIndex]} />);
            });
        }
    }

    render() {
        let tabs = null;
        let content = null;
        if (this.props.tabs) {
            tabs = this.renderTabs();
            content = this.renderConentActiveTab();
        }
        return (
            <div>
                <AppBar position="static" color="default">
                    <Tabs
                        value={this.state.value}
                        onChange={this.handleChange}
                        indicatorColor="primary"
                        textColor="primary"
                        centered
                        scrollButtons="auto"
                    >
                        {tabs}
                    </Tabs>
                </AppBar>
                <div className="productWidget">
                    <div className="wrapper">
                        {content}
                    </div>
                </div>
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        products: state.product.products,
    }
}

export default connect(mapStateToProps)(ProductsTabsWidget);

我试图为这个组件编写适当的测试,代码如下:

import React from 'react';

import {configure, shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ProductsTabsWidget from "./ProductsTabsWidget";


configure({adapter: new Adapter()});

describe('ProductsTabsWidget - component', () => {
    let wrapper;


    beforeEach(() => {
        wrapper = shallow(<ProductsTabsWidget/>);
    });

    it('renders with minimum props without exploding', () => {
        wrapper.setProps({
            tabs: [],
            products:[]
        });
        expect(wrapper).toHaveLength(1);
    });
})

但是当我运行测试时,我收到错误:

Test suite failed to run

    F:\PRACA\reactiveShop\node_modules\@material-ui\core\es\AppBar\AppBar.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _extends from "@babel/runtime/helpers/builtin/extends";
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at new Script (vm.js:51:7)
      at Object.<anonymous> (src/components/product/ProductsTabsWidget/ProductsTabsWidget.js:3:15)

我试过用shallow,进行测试mountrender但没有帮助。我错过了什么?

我的应用程序是在create-react-app.

3个回答

当您使用@material-ui.

您必须使用@material-ui的内置 API。例如createMount, createShallow,createRender以便使用酶的shallow, mount& render

这些 API 建立在 之上enzyme,因此您不能enzyme直接用于测试@material-ui


Shallow使用@material-ui 渲染的示例

import { createShallow } from '@material-ui/core/test-utils';

describe('<MyComponent />', () => {
  let shallow;

  before(() => {
    shallow = createShallow(); 
  });

  it('should work', () => {
    const wrapper = shallow(<MyComponent />);
  });
});

参考:@material-ui 的官方文档

以下是从create-react-app@material-ui角度提供更完整答案的谦虚尝试

1.setupTests.js直接在src文件夹中创建并粘贴以下代码。

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

configure({ adapter: new Adapter() });

2.以下是使用material-ui组件的react无状态组件。

import React from "react";
import TextField from "@material-ui/core/TextField";

const SearchField = props => (
   <TextField InputProps={{ disableUnderline: true }} fullWidth
              placeholder={props.placeholder}
              onChange={props.onChange}
   />
);

export default SearchField;

注意,在上面的组件中,组件期望父组件传递 props forplaceholderonChange()event handler

3.对于上述组件的测试用例,我们可以以一种material-ui建议的方式或一种pure enzyme风格来编写两者都会起作用。

Pure Enzyme 风格

import React from "react";
import { mount } from "enzyme";
import TextField from "@material-ui/core/TextField";
import SearchField from "../SearchField";
describe("SearchField Enzyme mount() ", () => {
  const fieldProps = {
    placeholder: "A placeholder",
    onChange: jest.fn()
  };
  const Composition = props => {
    return <SearchField {...fieldProps} />;
  };

  it("renders a <TextField/> component with expected props", () => {
    const wrapper = mount(<Composition />);
    expect(wrapper.childAt(0).props().placeholder).toEqual("A placeholder");
    expect(wrapper.childAt(0).props().onChange).toBeDefined();
  });
  it("should trigger onChange on <SearchField/> on key press", () => {
    const wrapper = mount(<Composition />);
    wrapper.find("input").simulate("change");
    expect(fieldProps.onChange).toHaveBeenCalled();
  });
  it("should render <TextField />", () => {
    const wrapper = mount(<Composition />);
    expect(wrapper.find(TextField)).toHaveLength(1);
    expect(wrapper.find(TextField).props().InputProps.disableUnderline).toBe(
      true
    );
  });
});

Material UI 风格

import React from "react";
import { createMount } from "@material-ui/core/test-utils";
import TextField from "@material-ui/core/TextField";
import SearchField from "../SearchField";
describe("SearchField", () => {
  let mount;
  const fieldProps = {
    placeholder: "A placeholder",
    onChange: jest.fn()
  };
  beforeEach(() => {
    mount = createMount();
  });

  afterEach(() => {
    mount.cleanUp();
  });

  it("renders a <TextField/> component with expected props", () => {
    const wrapper = mount(<SearchField {...fieldProps} />);
    expect(wrapper.props().placeholder).toEqual("A placeholder");
    expect(wrapper.props().onChange).toBeDefined();
  });
  it("should trigger onChange on <SearchField/> on key press", () => {
    const wrapper = mount(<SearchField {...fieldProps} />);
    wrapper.find("input").simulate("change");
    expect(fieldProps.onChange).toHaveBeenCalled();
  });
});

5.您收到的错误是由于babel没有机会处理您的文件。create-react-app希望你运行测试,如yarn run test不喜欢jest your/test/file.js如果您使用后者,babel则不会是employed.

如果你想用它jest来运行这个文件,你必须在 jest 尝试执行测试之前编写一个jest.config.js文件或jestpackage.json文件中配置使用babel-jest+other babel dependencies来转换你的代码。

昨天我和我@material-ui第一次尝试使用时在同一条船上,来到这里以获得更完整的答案。

这样的事情对我有用:

import {createMount} from '@material-ui/core/test-utils';

const WrappedComponent = () => 
    <MUIThemeStuffEtc>
        <MyComponent />
    </MUIThemeStuffEtc>

const render = createMount();
const wrapper = render(<WrappedComponent />);

const state = wrapper.find(MyComponent).instance().wrappedInstance.state