[React] Integration test a React component that consumes a Render Prop

本文介绍如何利用Enzyme和Jest的快照功能为名为CounterConsumer的React组件编写集成测试。该组件接收初始值,并通过按钮控制计数器的增减。测试确保组件正确渲染及响应点击事件。

In this lesson, I use Enzyme and Jest's Snapshot functionality to write an integration test for a component called CounterConsumer that consumes the Render Prop component Counter. This integration test is great because it doesn't necessarily care that CounterConsumer uses Counter behind the scenes, just that it works when integrated.

 

import React from "react";
import Counter from "./Counter";

export default function CounterConsumer({ initial }) {
  return (
    <Counter initial={initial}>
      {({ increment, decrement, counter }) => (
        <div className="content" style={{ textAlign: "center" }}>
          <h1>{counter}</h1>
          <button className="button is-success" onClick={increment}>
            Increment
          </button>
          <button className="button is-danger" onClick={decrement}>
            Decrement
          </button>
        </div>
      )}
    </Counter>
  );
}

 

test:

import React from "react";
import ReactDOM from "react-dom";
import toJSON from "enzyme-to-json";
import { mount } from "enzyme";
import "./enzymeSetup";
import CounterConsumer from "./CounterConsumer";

it("accepts an initial value", () => {
  const wrapper = mount(<CounterConsumer initial={1999} />);
  expect(toJSON(wrapper)).toMatchSnapshot();
});

it("increments counter", () => {
  const wrapper = mount(<CounterConsumer />);
  wrapper
    .find("button")
    .at(0)
    .simulate("click");

  expect(toJSON(wrapper)).toMatchSnapshot();
});

it("decrements counter", () => {
  const wrapper = mount(<CounterConsumer />);
  wrapper
    .find("button")
    .at(1)
    .simulate("click");

  expect(toJSON(wrapper)).toMatchSnapshot();
});

 

转载于:https://www.cnblogs.com/Answer1215/p/8457885.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值