用React编写JEST单元测试

时间:2019-03-18 12:21:44

标签: reactjs jestjs

我是单元测试的新手,将非常感谢您的帮助。 以下是组件

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

检查组件的值设置。

我该如何开玩笑和酶呢?

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

project-ID@appspot.gserviceaccount.com

1 个答案:

答案 0 :(得分:2)

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

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

Enzyme(来自airbnb)使此操作变得容易。看看他们有here

的文本方法

示例(来自文档)

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

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

编辑1

您应该可以通过酶中的find函数找到浅浅的渲染元素

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

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

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

相关问题