【问题标题】:Enzyme error 'ShallowWrapper can only wrap valid elements' on shallow functional component浅功能组件上的酶错误“ShallowWrapper 只能包装有效元素”
【发布时间】:2020-03-10 12:54:45
【问题描述】:

(我使用的是 React 16.11.0 和 Enzyme 3.10)

我在

中有一个 React.js 无状态功能组件
Product.js     

import React from 'react';

export const Product = ({productName}) => { 
   return (
      <div>
          <span class='product-name'>{productName}</span>
      <div>
   );

我正在尝试像这样使用 Enzyme Shallow 进行测试 Product.spec.js

import React from 'react';
import { shallow } from 'enzyme';
import { Product } from "./Product.js";

let props;

beforeEach(() => {
    props = {
        productName: "Bicycle"
    };
});

describe('Product', () => {
   it('should have productName', () => {
      const wrapper = shallow(<Product {...props} />);
      expect(wrapper.find('.product-name').length).toEqual(1);
   });
}

但是当测试运行时,酶会抛出这个错误:

TypeError: ShallowWrapper can only wrap valid elements

如果我像这样重写 Product.js,它可以正常工作,所以想知道为什么

function Product(props) { 
   return (
      <div>
          <span class='product-name'>{props.productName}</span>
      <div>
   );
export Product

【问题讨论】:

    标签: reactjs enzyme react-functional-component


    【解决方案1】:

    您应该在测试文件中导入您的组件。

    import {Product} from "./Product.js";
    

    【讨论】:

    • 好地方!我的实际代码已经有了,但我忘了添加到问题中......我现在已经更新了。谢谢:)
    猜你喜欢
    • 2019-05-02
    • 2020-12-31
    • 2019-08-11
    • 1970-01-01
    • 2019-01-16
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多