Help us understand the problem. What is going on with this article?

React Jest enzymeのテスト早見表(今後追加予定ver2019/10/17)

この記事について

Reactのテストを書くときにみる早見表

前提

テスト対象コンポーネント(tsx)

index.tsx
import * as React from 'react'

type TestProps = {
  propsNum: number
  onProps: () => void
}

type TestState = {
  stateNum: number
  stateBool: boolean
}

class TestComponent extends React.Component<TestProps, TestState> {
  constructor(props: TestProps) {
    super(props: TestProps)
    this.state = {
      stateNum: number,
      stateBool: boolean,
    }
  }

  handleOnClick = () => {
    this.setState({ stateNum: stateNum + 1 })
    this.props.onProps()
  }

  render() {
    return(
      <div className="TestComponent">
        <button className="button-element button-element2" onClick={this.handleOnClick} />
      </div>
    )
  }
}

export default TestComponent

テストコードは次のようになっている

test.jsx
import React from 'react'
import { shallow } from 'enzyme'
import Stepper from '.' // テスト対象のコンポーネントは同じ階層のディレクトリにあると仮定して

describe('<TestComponent />' () => {
  let wrapper
  let propsNum
  let onProps

  beforeEach(() => {
    propsNum = 0
    onProps = jest.fn()
    wrapper = shallow(<TestComponent propsNum={propsNum} onProps={onProps} />
  })
  // === ここにテストを追加していく ===
}

propsを変更する

wrapper.setProps({
  propsNum: 1
})

stateを変更する

wrapper.setState({
  stateNum: 1
})

stateが期待通りの値かをテストする

expect(wrapper.state('stateNum')).toBe(0)

コンポーネント内にあるhandleとかをテストする

wrapper.instance().handleOnClick()

あるクラスが存在するかをチェックする

expect(wrapper.find(.button-element).length).toBe(1)

次のようにすると、より厳密

expect(wrapper.find(.button-element.button-element).length).toBe(1)

ボタンをクリックする

wrapper.find('.button-element').simulate('click')
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away