【问题标题】:Testing react-hotkeys using react-testing-library使用 react-testing-library 测试 react-hotkeys
【发布时间】:2019-05-21 18:41:47
【问题描述】:

https://github.com/greena13/react-hotkeys

https://github.com/kentcdodds/react-testing-library

我无法触发热键(开玩笑)。一个演示组件:

import React from 'react';
import { HotKeys } from 'react-hotkeys';

class TestComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { enterClicked: false };
  }

  render() {
    const { enterClicked } = this.state;
    return (
      <HotKeys
        handlers={{
          enter: (e) => {
            console.log('ENTER', e);
            this.setState({ enterClicked: true });
          },
        }}
      >
        <input placeholder="input" type="text" />
        {enterClicked && <div>Enter clicked</div>}
      </HotKeys>
    );
  }
}

export default TestComponent;

这是一个测试:

import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';

import TestComponent from './TestComponent';

afterEach(cleanup);

describe('Test', () => {
  it('Hotkeys', () => {
    const { debug, getByPlaceholderText, getByText } = render(<TestComponent />);
    const inputNode = getByPlaceholderText('input');
    fireEvent.keyDown(inputNode, { key: 'Enter', keyCode: 13, code: 13, bubbles: true });
    debug();
    waitForElement(() => getByText('Enter clicked'));
  });
});

这是我的笑话设置文件:

/* global jest */
import { JSDOM } from 'jsdom';
import 'jest-localstorage-mock';
import dotenv from 'dotenv';

dotenv.config({ path: '../.env' });

const jsdom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'https://example.com' });
const { window } = jsdom;
window.location.reload = jest.fn();
window.location.assign = jest.fn();

function copyProps(src, target) {
  const props = Object.getOwnPropertyNames(src)
    .filter((prop) => typeof target[prop] === 'undefined')
    .reduce(
      (result, prop) => ({
        ...result,
        [prop]: Object.getOwnPropertyDescriptor(src, prop),
      }),
      {},
    );
  Object.defineProperties(target, props);
}

if (!window.attachEvent) {
  // eslint-disable-next-line func-names
  const attachEvent = function(on, callback) {
    on = on.substring(2, on.length);
    return this.addEventListener(on, callback);
  };

  window.Element.prototype.attachEvent = attachEvent;
}

if (!window.detachEvent) {
  // eslint-disable-next-line func-names
  const detachEvent = function(on, callback) {
    on = on.substring(2, on.length);
    return this.removeEventListener(on, callback);
  };

  window.Element.prototype.detachEvent = detachEvent;
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
  platform: 'Mac',
};
copyProps(window, global);

global.fetch = require('jest-fetch-mock');

global.requestAnimationFrame = (cb) => {
  setTimeout(cb, 0);
};

global.cancelAnimationFrame = (cb) => {
  setTimeout(cb, 0);
};

有什么想法吗?

【问题讨论】:

    标签: javascript reactjs testing hotkeys react-testing-library


    【解决方案1】:

    我是这样工作的:

    我在HotKeys-组件本身上放了一个测试ID:

    <HotKeys
      data-testid="hot-keys-id"
      ...
    

    然后我聚焦组件,然后手动创建了一个事件:

    const hotkeys = await waitForElement(() => getByTestId('hot-keys-id'));
    hotkeys.focus();
    
    const keyDownEvent = new Event('keydown');
    keyDownEvent.keyCode = 13;
    keyDownEvent.key = 'Enter';
    keyDownEvent.code = 13;
    
    hotkeys.dispatchEvent(keyDownEvent);
    

    【讨论】:

    • 我遇到了同样的问题。但不幸的是,您的解决方案对我不起作用。我有最新版本的react-hotkeys。如果我弄明白了,我会回复。但如果你有更新,请分享! :)
    • 很遗憾没有更新,抱歉!这些天来,我倾向于非渲染单元测试 + e2e 测试,而不是反应渲染测试,因为它们太麻烦了。但我很想听听你的发现!
    • 射击,这对我来说是一个愚蠢的错误。我没有在HotKeys 元素上使用waitForElement(就像你所做的那样)来确保它在调用dispatchEvent 之前被渲染。我不知何故错过了。不过谢谢!现在工作。
    猜你喜欢
    • 2019-11-11
    • 2019-08-29
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2021-11-30
    • 2021-04-26
    • 2021-02-11
    相关资源
    最近更新 更多