React Hooks 组件 Jest写法

React 拥有了更加强大的 Hooks书写方式,本人公司基本都抛弃使用class组件写法,随之jest单元测试写法也有些变化。

下面上一个demo

// demo.js


import React from 'react';

const TestComponent = () => {
  const [count, setCount] = React.useState(0);

  return (
    <h3>{count}</h3>
    <span>
      <button id="count-up" type="button" onClick={() => setCount(count + 1)}>Count Up</button>
      <button id="count-down" type="button" onClick={() => setCount(count - 1)}>Count Down</button>
      <button id="zero-count" type="button" onClick={() => setCount(0)}>Zero</button>
    </span>
  );
}

export default TestComponent;


// demo.test.js

import React from 'react';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import TestComponent from './FunctionalComponent';

Enzyme.configure({ adapter: new Adapter() });

describe('<TestComponent />', () => {
  let wrapper;
  const setState = jest.fn();
  const useStateSpy = jest.spyOn(React, 'useState')
  useStateSpy.mockImplementation((init) => [init, setState]);

  beforeEach(() => {
    wrapper = Enzyme.shallow(<TestComponent />);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('Count Up', () => {
    it('calls setCount with count + 1', () => {
      wrapper.find('#count-up').props().onClick();
      expect(setState).toHaveBeenCalledWith(1);
    });
  });

  describe('Count Down', () => {
    it('calls setCount with count - 1', () => {
      wrapper.find('#count-down').props().onClick();
      expect(setState).toHaveBeenCalledWith(-1);
    });
  });

  describe('Zero', () => {
    it('calls setCount with 0', () => {
      wrapper.find('#zero-count').props().onClick();
      expect(setState).toHaveBeenCalledWith(0);
    });
  });
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值