首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-testing-library:由于输入而发生的更改

React-testing-library:由于输入而发生的更改
EN

Stack Overflow用户
提问于 2018-11-23 02:15:10
回答 1查看 16.4K关注 0票数 8

我正在尝试测试组件是否因输入元素中的更改而按其应有的方式进行更新。我使用fireEvent.change()-function,如果我随后使用getByPlaceholderText检查我找到的节点的值,它已经按照应该的方式进行了更新。但是,我看不到react组件本身的变化。

这可能是因为更改直到重新渲染才会发生;我如何测试这一点?react-testing-library的rerender似乎是“从头开始”(即没有新的输入值),并且waitForElement永远不会找到它正在等待的东西。

下面是组件TestForm.js:

代码语言:javascript
复制
import React from 'react';
import { withState } from 'recompose';

const initialInputValue = 'initialInputValue';

const TestForm = ({ inputValue, setInputValue }) => (
  <>
    {console.log('inputValue', inputValue)}
    <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="placeholder" />
    {inputValue !== initialInputValue && <div>Input has changed</div>}
  </>
);

export default withState('inputValue', 'setInputValue', initialInputValue)(TestForm);

下面是测试,使用npx jest test.js运行

代码语言:javascript
复制
import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';

import TestForm from './TestForm';

afterEach(cleanup);

describe('TestForm', () => {
  it('Change input', async () => {
    const { getByPlaceholderText, getByText } = render(<TestForm />);
    const inputNode = getByPlaceholderText('placeholder');
    fireEvent.change(inputNode, { target: { value: 'new value' } });
    console.log('inputNode.value', inputNode.value);
    await waitForElement(() => getByText('Input has changed'));
  });
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-23 03:14:41

下面的代码适用于我:

代码语言:javascript
复制
import React from "react";

const initialInputValue = "initialInputValue";

class TestForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { inputValue: initialInputValue };
  }
  render() {
    const { inputValue } = this.state;

    return (
      <div>
        {console.log("inputValue", inputValue)}
        <input
          value={inputValue}
          onChange={e => this.setState({ inputValue: e.target.value })}
          placeholder="placeholder"
        />
        {inputValue !== initialInputValue && <div>Input has changed</div>}
      </div>
    );
  }
}

import { render, cleanup, fireEvent } from "react-testing-library";
import "jest-dom/extend-expect";

afterEach(cleanup);

test("form", () => {
  const { getByPlaceholderText, getByText } = render(<TestForm />);
  fireEvent.change(getByPlaceholderText("placeholder"), {
    target: { value: "new value" }
  });
  expect(getByText("Input has changed")).toBeInTheDocument();
});

虽然它不能在codesandbox中工作,但我猜他们在保持浏览器和测试环境分离方面有一些问题。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53436344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档