如何使用React和Jest模拟onPast事件?

问题描述 投票:0回答:1

我正在尝试在我的React项目上使用JEST测试来模拟粘贴事件。

我有一个外部组件“ App”,其中包含带有“ onPaste”事件的输入字段,我想测试过去的数据并检查输入值。

it("on past with small code", () => {

// Create new Security Code module
const wrapper = mount(<CodeVerification />);

const element = wrapper.find(".code-verification .code input");
const element1 = element.first();
element1.simulate("paste", { clipboardData: {value: "12"} });
});

在我的组件中,我调用剪贴板数据事件:

const pasteDatas = pastEvent.clipboardData || window.clipboardData;
const paste = pasteDatas.getData("text");

[执行测试时出现错误,因为

TypeError:pasteDatas.getData不是一个函数。

我如何模拟剪贴板事件数据并在JEST测试中获得输入值?

感谢您的回复。

javascript reactjs unit-testing jestjs enzyme
1个回答
0
投票

这是单元测试解决方案:

index.tsx

import React, { Component } from 'react';

class CodeVerification extends Component {
  constructor(props) {
    super(props);
    this.handlePaste = this.handlePaste.bind(this);
  }
  handlePaste(event: React.ClipboardEvent<HTMLInputElement>) {
    const pasteDatas = event.clipboardData || (window as any).clipboardData;
    const text = pasteDatas.getData('text');
    console.log(text);
  }
  render() {
    return (
      <div>
        <input type="text" onPaste={this.handlePaste} />
      </div>
    );
  }
}

export default CodeVerification;

index.test.tsx

import CodeVerification from './';
import { mount } from 'enzyme';
import React from 'react';

describe('60492514', () => {
  it('should handle paste event', () => {
    const wrapper = mount(<CodeVerification></CodeVerification>);
    const logSpy = jest.spyOn(console, 'log');
    const mEvent = { clipboardData: { getData: jest.fn().mockReturnValueOnce('12') } };
    wrapper.find('input').simulate('paste', mEvent);
    expect(mEvent.clipboardData.getData).toBeCalledWith('text');
    expect(logSpy).toBeCalledWith('12');
  });
});

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

 PASS  stackoverflow/60492514/index.test.tsx
  60492514
    ✓ should handle paste event (49ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    12

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |       75 |     100 |     100 |                   
 index.tsx |     100 |       75 |     100 |     100 | 9                 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.837s, estimated 10s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60492514

© www.soinside.com 2019 - 2024. All rights reserved.