javascript - React-testing-library:由于输入而发生的变化
问题描述
我正在尝试测试组件是否由于输入元素的更改而更新。我使用fireEvent.change()
-function,然后检查我发现使用getByPlaceholderText
它的节点的值是否已按应有的方式更新。但是我看不到反应组件本身的变化。
这可能是因为在重新渲染之前不会发生更改;我将如何测试这个?react-testing-libraryrerender
似乎“从头开始”启动组件(即没有新的输入值),并且waitForElement
永远找不到它正在等待的内容。
这是组件 TestForm.js:
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
:
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'));
});
});
解决方案
这段代码对我有用:
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();
});
虽然它在代码沙箱中不起作用,但我猜他们在保持浏览器和测试环境分离方面存在一些问题。
推荐阅读
- matlab - 如何根据任一向量的条件修改多个向量?
- javascript - 如何处理@jupyterlab/apputils 对话框点击事件 | Jupyterlab 扩展
- azure - 如何向 Azure 上的 VM 添加多个网卡?
- cypress - 通过打开和运行命令运行多个赛普拉斯规范时的不同行为
- sql - 如何检查是否为空,如果参数为空,则使用 IS NULL 检查值
- sql - 带有单选或多选且没有正确/错误答案的问卷的模式设计
- git - Git 历史包含许多以前接受的 PR 的提交
- oracle - Oracle plsql 触发器
- javascript - 是否使用“npm install -g my-package”安装了 devDependencies?
- docker - 使用上次启动时已经包含文件的卷在 docker 上运行 confluence