首页 > 解决方案 > TypeError: Function.prototype.name sham getter 仅在我使用 `--coverage` 运行时在非函数上调用

问题描述

当我运行测试时--coverage

 yarn run test --coverage

出现跟随错误

component › should render with message if error occour

TypeError: Function.prototype.name sham getter called on non-function

  14 |              );
  15 |
> 16 |              expect(wrapper).toMatchSnapshot();
     |                              ^
  17 |      });
  18 |
  19 |      it("should render if error occour", function() {

  at Function.getName (../node_modules/function.prototype.name/implementation.js:31:9)
  at displayNameOfNode (../node_modules/enzyme-adapter-utils/build/Utils.js:156:95)
  at ReactSixteenAdapter.displayNameOfNode (../node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:605:62)
  at typeName (../node_modules/enzyme/build/Debug.js:60:43)
  at internalNodeToJson (../node_modules/enzyme-to-json/mount.js:70:31)
  at mountToJson (../node_modules/enzyme-to-json/mount.js:93:12)
  at Object.<anonymous>.exports.default (../node_modules/enzyme-to-json/index.js:14:32)
  at Object.print (../node_modules/enzyme-to-json/createSerializer.js:22:40)
  at printPlugin (../node_modules/pretty-format/build/index.js:287:16)
  at prettyFormat (../node_modules/pretty-format/build/index.js:485:16)
  at Object.throwingMatcher (../node_modules/expect/build/index.js:320:33)
  at Object.toMatchSnapshot (src/components/molecules/ErrorBoundary/ErrorBoundary.test.jsx:16:19)

那是我的ErrorBoundary组件

import React from "react";

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    componentDidCatch(error, info) {
        this.setState(prevState => ({ ...prevState, hasError: true }));
    }

    render() {
        const { hasError } = this.state;
        const { children, message = "Ops, ocorreu um erro. Tente novamente" } = this.props;

        return hasError ? <h1>{message}</h1> : children;
    }
}

还有我的测试..

import React from "react";
import ErrorBoundary from "./ErrorBoundary";

describe("<ErrorBoundary> component", function() {
    it("should render with message if error occour", function() {
        function ProblemChild() {
            throw new Error("Error thrown from problem child");
        }

        const wrapper = mount(
            <ErrorBoundary message="Ops, algum erro ocorreu">
                <ProblemChild />
            </ErrorBoundary>
        );

        expect(wrapper).toMatchSnapshot();
    });
});

标签: unit-testingjestjsenzyme

解决方案


我刚刚在我的代码库中解决了这个问题。问题是由于导出时缺少类名引起的,因此您的修复可能是在ErrorBoundary组件中添加类名以及它丢失的任何其他地方。IE

改变:export default class extends React.Component {

至:export default class ErrorBoundary extends React.Component {

希望能帮助到你!


推荐阅读