简体   繁体   English

用React编写JEST单元测试

[英]Writing a JEST unit test with React

I am new to unit testing would really appreciate help. 我是新来的单元测试人员,将不胜感激。 Below is the component 以下是组件

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

I want to write a test scenario in regards to the 我想写一个关于

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

that checks for the components has value setup. 检查组件的值设置。

How can I do this with jest and enzyme? 我该如何开玩笑和酵素?

I have tried the code for tests as below : 我已经尝试了以下测试代码:

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');
  }); 
});

Don't test the framework, test your logic 不要测试框架,请测试您的逻辑

If you pass a value as a prop it will have that as a prop. 如果您将值作为支撑传递,它将具有该支撑。 There is no need to test this. 无需测试。 You're essentially writing a test for react itself. 您实际上是在编写一个用于测试自身反应的测试。 You can however see what value exists inside your component. 但是,您可以看到组件内部存在什么值。

Enzyme

This is made easy with Enzyme (from airbnb) . 使用 (来自airbnb)可以轻松做到这一点。 Check out the text method they have here 在这里查看他们使用的文本方法

Example (from docs) 示例(来自docs)

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

You can test this.props.value easily with this. 您可以轻松地测试this.props.value

Edit 1 编辑1

You should be able to find the shallow rendered element via the find function in Enzyme 您应该能够通过Enzyme中的find函数找到浅浅的渲染元素

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

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

Perhaps it can be combined with the text function. 也许可以将其与text功能结合使用。 I don't have an on hand example/sandbox right now. 我现在没有手头的示例/沙盒。

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

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