标签: react-testing-library

react-testing-library validateDOMNesting 错误

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>.
    in tbody (created by TableBody)
    in TableBody (created by TableBody)
    in TableBody
Run Code Online (Sandbox Code Playgroud)

题:

如何使我的TableBody分量的table元素,而不是默认的div那个react-testing-library用途?

补充资料:

我尝试将选项传递给react-testing-library, render(), 函数,但我似乎无法让它工作。

我还尝试在react-testing-library测试中挖掘以查找示例,但没有找到任何东西。

// react-testing-library

function render(
  ui: React.ReactElement<any>,
  options?: {
    /* You wont often use this, expand below for docs on options */
  },
): RenderResult
Run Code Online (Sandbox Code Playgroud)

来自 react-testing-library 文档

您通常不需要指定选项,但如果您需要,这里有可用选项,您可以将其作为渲染的第二个参数提供。

container:默认情况下,react-testing-library将创建一个div并将其附加div到document.body,这是您的反应组件将被呈现的地方。如果您 …

javascript unit-testing reactjs jestjs react-testing-library

5
推荐指数
1
解决办法
1071
查看次数

Jest mocking - 模拟命名导出,除了一个

我有一个 redux 文件,其中包含我的减速器和我通过命名导出的所有操作。

export const reducer = (state, action) => ...

export myAction = action => {
    return {type: 'ACTION', action}
}
...
Run Code Online (Sandbox Code Playgroud)

在我的测试文件中,我导入了减速器和操作。我有一个 renderWithRedux,它接收 reducer 并在里面创建一个真正的store。

function renderWithRedux(ui, reducer = combineReducers(reducers), initialState = {}) {
    const store = createStore(reducer, initialState)
    const utils = render(<Provider store={store}>{ui}</Provider>)

    return {
        ...utils,
        store,
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我正在渲染的组件是在连接组件的 mapDispatchToProps 中传递的动作。

export default connect(mapStateToProps, { myAction })(MyComponent)
Run Code Online (Sandbox Code Playgroud)

我想在我的特定用例中模拟myAction这个动作实际上是一个 thunk,我想看看商店是否更新。

我的问题是如何模拟 myAction 而不是减速器。我试过了

jest.mock('./reducerFile', () => {
    return jest.fn().mockImplementation(() => {
        return { …
Run Code Online (Sandbox Code Playgroud)

jestjs react-redux react-testing-library

5
推荐指数
2
解决办法
3855
查看次数

在测试 React 组件时模拟 Redux 存储?

我正在使用 React 和 Redux。我有一个加载的组件,ChildComponent根据 Redux 的状态也会加载MainComponent

    const ChooseIndex = ({ appInitMount }) => {
      return (
        <>
          <ChildComponent />
          {!appInitMount && <MainComponent />}
        </>
      );
    };


    const mapStateToProps = ({ main }) => {
      return {
        appInitMount: main.appInitMount
      };
    };

    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(ChooseIndex);
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个测试来检查是否ChildComponent已加载:

    import React from "react";
    import { render } from "react-testing-library";
    import ChooseIndex from "../choose-index";

    test("ChooseIndex should call ChildComponent", () => {
      const wrapper = render(
        <ChooseIndex />
      ); …
Run Code Online (Sandbox Code Playgroud)

testing reactjs redux react-testing-library

5
推荐指数
1
解决办法
6446
查看次数

如何使用React-Testing-Library选中Material-UI Checkbox?

似乎Material UI的工作方式是单击复选框时呈现了一个不同的SVG,而不更改属性或实际输入元素上的任何内容。那么,我该如何实际测试该元素是否按照react-testing-library哲学进行了检查?

这是一个粗略的例子

// Checkbox component usage
export const CheckBoxContainer = () => 
<Checkbox
  inputProps={{ 'data-testid': `clickable-checkbox-1234` }}
  data-testid={`checkbox-1234`}
/>

// test
test('check the box', async () => {
  const { getByTestId } = render(<CheckBoxContainer />);
  await waitForElement(() => getByTestId(`checkbox-1234`));
  const checkbox = getByTestId(`checkbox-1234`);
  fireEvent.click(getByTestId(`clickable-checkbox-1234`));
  expect(checkbox).toHaveAttribute('checked');
});

// Generated HTML by Material UI
<span class="MuiButtonBase-root-54 MuiIconButton-root-48 MuiSwitchBase-root-231 MuiCheckbox-root-225 MuiCheckbox-colorSecondary-230 MuiSwitchBase-checked-232 MuiCheckbox-checked-226" data-testid="checkbox-1234">
  <span class="MuiIconButton-label-53">
    <svg class="MuiSvgIcon-root-57" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation">
      <path d="M19 3H5c-1.11 0-2 .9-2 …
Run Code Online (Sandbox Code Playgroud)

material-ui react-testing-library

5
推荐指数
2
解决办法
2233
查看次数

react-testing-library-fireEvent.select()不起作用

我目前正在为我正在从事的项目运行一些测试,但在使用fireEvent.select()这种方法专注于输入字段时遇到了麻烦。

到目前为止,我的测试:

it('is not working :(', () => {
  const input = queryByPlaceholderText('blah');

  fireEvent.change(input, {
    target: {value: 'some text'},
  });

  expect(input).toHaveAttribute('value', 'some text');

  fireEvent.select(input); <-- issue here
});
Run Code Online (Sandbox Code Playgroud)

我正在测试的组件具有一个下拉菜单,该菜单仅在输入集中时才显示,但似乎fireEvent.change()也不fireEvent.select()在现场。我知道这会fireEvent.change()改变输入值。

到目前为止,我已经尝试过:

  • fireEvent.click()
  • fireEvent.focus()
  • fireEvent.select()
  • input.focus()

但这些选项均无效。

我需要能够在此下拉菜单中选择一个选项,以便能够正确测试组件。

TL; DR

有没有一种方法可以专注于RTL的输入字段?

javascript reactjs jestjs react-testing-library

5
推荐指数
1
解决办法
2019
查看次数

如何在react-testing-library中的单选按钮上触发更改事件?

我正在转移到react-testing-library,并且不知道如何触发此事件并获取更改结果。

我试过使用该fireEvent函数触发更改,然后尝试了该rerender函数,但是我似乎无法使其正常工作。

App.js

import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";

const options = {
  DoTheThing: 'DoTheThing',
  DoOtherThing: 'DoOtherThing',
};

function App() {
  const [action, setAction] = useState(options.DoTheThing);

  return (
    <div className="App">
      <header className="App-header">
        <form>
          <fieldset>
            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoTheThing}
                checked={action === options.DoTheThing}
                onChange={event => setAction(event.target.value)}
              />
              First
            </label>

            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoOtherThing}
                checked={action === options.DoOtherThing}
                onChange={event => setAction(event.target.value)}
              />
              Second
            </label>
          </fieldset>
        </form>
      </header>
    </div>
  );
}

export …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

5
推荐指数
3
解决办法
2806
查看次数

玩笑没有定义

我目前正在用打字稿制作一个反应应用程序,我正在使用 react-testing-library 进行测试。该应用程序崩溃ReferenceError: jest is not defined。不过我所有的测试都通过了。

以前,一切正常。唯一改变的是我重新组织了一些文件。

代码:

import { FormProps } from "../containers";

const onChange = jest.fn(); // The problem
const history: any = jest.fn();
const location: any = jest.fn();
const match: any = jest.fn();

const TestProps: FormProps = {
  onChange,
  history,
  location,
  match,
};

export default TestProps;
Run Code Online (Sandbox Code Playgroud)

typescript reactjs jestjs react-testing-library

5
推荐指数
1
解决办法
4238
查看次数

React 测试库 fireEvent.change 不适用于 fireEvent.submit

tldr; fireEvent.change 有效,但在表单提交时,未在提交处理程序中找到新值。

假设我们有一个简单的形式:

// MyForm.tsx
class MyForm extends React.Component {
  state = { data: '123' }
  handleChange = (e: any) => {
    // This never gets fired in the test, why?
    console.log('HandleChange Fired', e.target.value)
    this.setState({ data: e.target.value })
  }
  handleSubmit = () => {
    console.log('************* HandleSubmit Fired **************', this.state)
  }
  render() {
    return (
      <form name="address" onSubmit={this.handleSubmit}>
        <input name="title" value={this.state.data} onChange={this.handleChange} />
        <button type="submit">Submit</button>
      </form>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

和断言表单提交值的测试是准确的:

// MyForm.spec.tsx
import React from 'react'
import { expect } …
Run Code Online (Sandbox Code Playgroud)

testing mocha.js reactjs react-testing-library

5
推荐指数
0
解决办法
1621
查看次数

使用 Jest 运行测试时无法访问窗口属性

我正在尝试访问位于window.sunpietro.configproperty下的property。使用 Jest 运行测试时,我得到TypeError: Cannot read property 'config' of undefined.

我的测试代码如下所示:

import React from 'react';
import { render, cleanup } from 'react-testing-library';
import MyModule from '../my.module';
import { myConfigMock } from '../../../../jest.window.mock';

afterEach(cleanup);
beforeEach(() => {
    window.sunpietro = { ...myConfigMock };

    // window.sunpietro.config = {};
});

describe('MyModule', () => {
    test('The module renders correctly', () => {
        const { getByTestId } = render(<MyModule />);

        getByTestId('my-tabs').toBeDefined();
        getByTestId('my-panels').toBeDefined();
    });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用最新版本的 Jest:24.7.1和react-testing-library版本:6.1.2.

我如何模拟 …

unit-testing reactjs jestjs react-testing-library

5
推荐指数
1
解决办法
1010
查看次数

React-Testing-Library - 用 Redux 和路由器包装组件

我正在尝试设置一个测试文件以在我的应用程序上呈现路由/页面。我正在尝试使用 Redux 和 Router 包装所有内容,这就是我所拥有的:

import React from 'react';
import { render } from 'react-testing-library';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from '../../store/reducer';
import {Link, Route, Router, Switch} from 'react-router-dom'
import {createMemoryHistory} from 'history'

import ViewNode from '../Pages/ViewNode';


const customRender = (
  ui,
  {
    route = '/',
    history = createMemoryHistory({ initialEntries: [route] }),
    initialState,
    store = createStore(reducer, initialState),
    ...options
  } = {}
) => ({
  ...render(
    <Provider store={store}>
      <Router history={history}>{ui}</Router>
    </Provider>,
    options …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router react-redux react-testing-library

5
推荐指数
1
解决办法
4091
查看次数