使用ReactTestUtils模拟点击不起作用

时间:2018-10-19 07:17:10

标签: reactjs testing jestjs

我正在尝试仅使用Jest和ReactTestUtils编写测试。如何正确模拟点击?我不想使用酶并坚持默认情况下CRA给我的东西。

按钮是一个无状态组件(函数),无法正确安装它,但现在是一个类,仍然无法使用“模拟”行...

`import React from 'react';
import * as TestRenderer from 'react-test-renderer';
import ReactTestUtils from 'react-dom/test-utils';

import { Button } from '..';

let renderer: TestRenderer.ReactTestRenderer;
let instance: TestRenderer.ReactTestInstance;

const button = <Button text="TextButton" />;

describe('Button', () => {
  beforeAll(() => {
    renderer = TestRenderer.create(button);
    instance = renderer.root;
  });

  it('renders with correct props', () => {
    const buttonProps = instance.findByType('button').props.children;

    expect(buttonProps).toBe('TextButton');
  });

  it('executes onClick function', () => {
    const clickHandler = jest.fn();
    const element = ReactTestUtils.renderIntoDocument(
      <Button onClick={clickHandler} />,
    );
    const buttonElement = 
      ReactTestUtils.findRenderedDOMComponentWithTag(element, 
      'button');

    // This line returns 'undefined'
    ReactTestUtils.Simulate.click(buttonElement);

    // Returns: Expected mock function to have
    // been called one time, but it was called zero times
    expect(clickHandler).toHaveBeenCalledTimes(1);
  });
})`

有什么主意吗?我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我不知道您的Button实现是什么。但是下面的示例对我有用。

Button.tsx

import React, { Component } from 'react';

export interface IButtonOwnProps {
  text: string;
  onClick(): void;
}

export class Button extends Component<IButtonOwnProps> {
  public static defaultProps: IButtonOwnProps = {
    text: '',
    onClick: () => {}
  };
  public render() {
    return <button onClick={this.props.onClick}>{this.props.text}</button>;
  }
}

Button.spec.tsx

import React from 'react';
import TestRenderer, { ReactTestRenderer, ReactTestInstance } from 'react-test-renderer';
import ReactTestUtils from 'react-dom/test-utils';
import { Button, IButtonOwnProps } from './Button';

describe('Button', () => {
  let testRenderer: ReactTestRenderer;
  let instance: ReactTestInstance;
  beforeAll(() => {
    testRenderer = TestRenderer.create(<Button text="TextButton" />);
    instance = testRenderer.root;
  });

  it('renders with correct props', () => {
    const buttonProps = instance.findByType('button').props.children;
    expect(buttonProps).toBe('TextButton');
  });

  it('executes onClick function', () => {
    const clickHandler = jest.fn();
    const element = ReactTestUtils.renderIntoDocument<IButtonOwnProps, Button>(<Button onClick={clickHandler} />);
    const buttonElement = ReactTestUtils.findRenderedDOMComponentWithTag(element, 'button');
    ReactTestUtils.Simulate.click(buttonElement);
    expect(clickHandler).toHaveBeenCalledTimes(1);
  });
});

带有覆盖率报告的单元测试结果:

PASS  src/stackoverflow/52887470/Button.spec.tsx
  Button
    ✓ renders with correct props (4ms)
    ✓ executes onClick function (14ms)

------------|----------|----------|----------|----------|-------------------|
File        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files   |      100 |      100 |    66.67 |      100 |                   |
 Button.tsx |      100 |      100 |    66.67 |      100 |                   |
------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.076s, estimated 5s

以下是完整的演示:__pragma