简体   繁体   中英

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) . Check out the text method they have here

Example (from docs)

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

You can test this.props.value easily with this.

Edit 1

You should be able to find the shallow rendered element via the find function in Enzyme

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. I don't have an on hand example/sandbox right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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