繁体   English   中英

用React编写JEST单元测试

[英]Writing a JEST unit test with React

我是新来的单元测试人员,将不胜感激。 以下是组件

import React from 'react';
import PropTypes from "prop-types";
import {Textfit} from 'react-textfit'; //This will fit the text how big or small it is.

class DisplayPanel extends React.Component {
    render() { 
        return (
            <Textfit className="calculator-display">{this.props.value}</Textfit>
        );
    }
}

DisplayPanel.propTypes = {
    value: PropTypes.string,
};

export default DisplayPanel

我想写一个关于

<Textfit className="calculator-display">{this.props.value}</Textfit>

检查组件的值设置。

我该如何开玩笑和酵素?

我已经尝试了以下测试代码:

import React from "react";
import { shallow } from "enzyme";
import DisplayPanel from "../components/DisplayPanel";
import { Textfit } from "react-textfit";

describe("Display Panel", () => {
  let wrapper;
  beforeEach(() => (wrapper = shallow(<DisplayPanel/>)));

  it("should render correctly", () => expect(wrapper).toMatchSnapshot());

  it("should render a Textfit component", () => {
    expect(wrapper.containsMatchingElement(<Textfit />)).toEqual(true);
  });

   //what should come here
   it("renders the value", () => {
    //expect(wrapper.text()).toEqual('0');
  }); 
});

不要测试框架,请测试您的逻辑

如果您将值作为支撑传递,它将具有该支撑。 无需测试。 您实际上是在编写一个用于测试自身反应的测试。 但是,您可以看到组件内部存在什么值。

使用 (来自airbnb)可以轻松做到这一点。 在这里查看他们使用的文本方法

示例(来自docs)

const wrapper = mount(<div><b>important</b></div>);
expect(wrapper.text()).to.equal('important');

您可以轻松地测试this.props.value

编辑1

您应该能够通过Enzyme中的find函数找到浅浅的渲染元素

import Foo from '../components/Foo';

const wrapper = mount(<MyComponent />);
expect(wrapper.find(Foo)).to.have.lengthOf(1);

也许可以将其与text功能结合使用。 我现在没有手头的示例/沙盒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM