标签: react-testing-library

尝试测试组件时找不到模块“反应”

我正在尝试向我的应用程序添加一些测试,但是当我安装react-testing-libraryand 时jest-dom,我编写了这个测试, test ifcomponentDidMount被调用:

import { render } from "react-testing-library";

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

it("should call componentDidMount", () => {
  const cDM = jest.spyOn(QuestionContainer.prototype, "componentDidMount");

  render(QuestionContainer);

  expect(cDM).toHaveBeenCalled(1);
});
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

Cannot find module 'react' from 'index.js'

However, Jest was able to find:
    '../containers/QuestionContainer.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].
Run Code Online (Sandbox Code Playgroud)

我不认为文件扩展名有问题..

javascript testing reactjs react-testing-library

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

如何将 Material-UI 样式表注入 jest/react-testing-library 测试?

似乎如果您不将 Material-UI 样式表注入 jest/react-testing-library 测试,那么 jsdom 将无法从您的组件中获取正确的样式(例如,运行getComputedStyle(component)将返回不正确的组件样式)。

您如何正确设置 jest/react-testing-library 测试,以便将样式正确地注入到测试中?我已经将组件包装在主题提供程序中,效果很好。

jestjs material-ui react-testing-library

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

Jest:如何模拟从 index.js 文件导出的自定义模块?

这是我的项目(create-react-app)的结构:

在此处输入图片说明

/src/api/searchAPI.js 的内容:

import client from './client';

async function searchMulti(query, options = {}) {
  options.query = query;
  return await client.get('/search/multi', options);
}

export default {
  searchMulti
};
Run Code Online (Sandbox Code Playgroud)

/src/api/index.js 的内容:

import movieAPI from './movieAPI';
import personAPI from './personAPI';
import searchAPI from './searchAPI';
import configurationAPI from './configurationAPI';

export { movieAPI, personAPI, searchAPI, configurationAPI };
Run Code Online (Sandbox Code Playgroud)

QuickSearch 组件导入searchAPI 并使用它通过网络获取一些数据。

现在,我需要测试(使用react-testing-library)QuickSearch 组件。

因此,我想模拟api模块(在 /src/api/index.js 中导出)以使用模拟函数而不是searchAPI.searchMulti()。

如果我将下面的代码放在 /src/componentns/__tests__/QuickSearch.js 中,它就可以正常工作:

...
import { searchAPI } from '../../
...
... …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing reactjs jestjs react-testing-library

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

使用 react-testing-library 测试具有动态内容的列表的惯用方法是什么

刚接触 RTL 并试图了解如何以地道的方式做事。我有一个包含动态元素的列表(它出现在某些行而不是其他行中)。

这是组件:

import React from 'react'
export default function DummyList ({ items }) {
  return <div>
    {items.map(item => <ListItem item={item} key={item.name} />)}
  </div>
}

export function ListItem ({ item: { name, isActive } }) {
  return <div data-testid='list-item'>
    <span>{name}</span>
    {isActive && <span>Active!</span>}
  </div>
}
Run Code Online (Sandbox Code Playgroud)

这是测试

import React from 'react'
import { render, getByText, queryByText, getAllByTestId } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import DummyList from './index'

describe('DummyList', () => {
  it('renders', async () => {
    const items = [
      { …
Run Code Online (Sandbox Code Playgroud)

testing reactjs react-testing-library

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

如何使用反应测试库测试回退

我正在寻找一种使用 react-testing-library 测试 React.Suspense 回退的方法。考虑这个例子:

const MyLazyThing = lazy(() => import('./index'));

export default function MyThing(props) {
  return (
    <Suspense fallback="loading...">
      <MyLazyThing {...props} />
    </Suspense>
  );
}
Run Code Online (Sandbox Code Playgroud)

使用getByText('loading...')似乎不起作用。想知道是否有一种在 RTL 中进行测试的好方法。

谢谢

fallback react-testing-library react-suspense

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

如何用玩笑模拟和测试链式函数?

我的组件 useEffect 钩子中有这个函数链。我将响应/数据设置为我的组件状态,以便我可以在我的组件中呈现数据。

client
  .items()
  .type("client")
  .toObservable()
  .subscribe(response => {
    setState(response)
  })
Run Code Online (Sandbox Code Playgroud)

我如何模拟这个函数并在组件在我的测试中呈现之前调用它?我正在使用测试库/反应。

回应是 {items: [{},...]}, somethingElse: {}

javascript mocking jestjs react-testing-library

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

使用react-testing-library在表单中提交时如何测试已调用的函数?

在我的 React Signup 组件中有一个表单,用户可以在其中输入他们的电子邮件、密码和密码确认。我正在尝试使用 jest/react-testing-library 编写测试,但是由于接收到的函数调用次数为 0,预期调用次数为 1,因此测试一直失败。

我尝试过 Jest 匹配器的变体,例如 .toHaveBeenCalled()、.toHaveBeenCalledWith(arg1, arg2, ...)、toBeCalled(),所有这些都仍然期望值为 1 或更大但失败,因为接收到的数字为 0。我已经尝试了 fireEvent.click 和 fireEvent.submit ,这两个都失败了。

注册.js

export const Signup = ({ history }) => {
  const classes = useStyles();

  const [signup, setSignup] = useState({
    email: null,
    password: null,
    passwordConfirmation: null,
  });
  const [signupError, setSignupError] = useState('');

  const handleInputChange = e => {
    const { name, value } = e.target;

    setSignup({ ...signup, [name]: value });
    console.log(signup);
  };

  const submitSignup = e => {
    e.preventDefault();
    console.log( …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

火灾事件后反应测试库没有清理

我们一直在使用 React 钩子useReducer并useContext在我们的React应用程序中处理全局存储。

在使用 react 测试库运行测试时,我们注意到一旦我们的状态在一个测试中发生变化,接下来的所有测试现在都会发生该状态变化。

我们曾尝试进行清理,afterEach(cleanup)但没有奏效。

不知道发生了什么?

import React, { useContext, useReducer } from 'react'
import { render, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import TodosList from './TodosList'
import reducer from '../../reducers/reducer'
import Store from '../../context'
import fixture from '../../tests/fixtures'

function Component() {
  const [state, dispatch] = useReducer(reducer, fixture)

  return (
    <Store.Provider value={{ state, dispatch }}>
      <TodosList />
    </Store.Provider>
  )
}

describe('todos', () => {
  it('removes a todo when button is pressed', () …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

使用 react 测试库测试 react-contenteditable

如何测试这个组件:https : //github.com/lovasoa/react-contenteditable?如何在测试环境中模仿用户操作?我试过以下:

// The given element does not have a value setter
fireEvent.change(sourceContent, {
  target: { value: "New content text" }
});

// This doesn't emit onChange Changes text content but onChange is not fired.
fireEvent.change(sourceContent, {
  target: { textContent: "New content text" }
});

// This doesn't emit onChange. Changes inner html but onChange is not fired.
fireEvent.change(sourceContent, {
  target: { innerHTML: "New content text" }
});
Run Code Online (Sandbox Code Playgroud)

以上都是失败的测试。我想如果我改变了innerHTML,那么提供的函数onChange将被触发。这是有这个问题的示例项目:https : //codesandbox.io/s/ecstatic-bush-m42hw?fontsize=14&hidenavigation=1&theme=dark

reactjs react-testing-library

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

ant design v4 打破了选择和自动完成的反应测试库测试

我最近将我的 React 项目升级到了 ant design v4,所有使用 Select、AutoComplete 或 Tooltip 的测试都被破坏了。基本上在单击组件时,JSDOM 中不存在模态或选择选项。这曾经在 v3 中工作正常。

有人可以告诉我如何使用反应测试库测试 antd v4 吗?

例子:

我的组件:

import React from "react";
import "./styles.css";
import { Select } from "antd";

const { Option } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

export default function App() {
  return (
    <div className="App" style={{ marginTop: "40px" }}>
      <Select
        defaultValue="lucy"
        style={{ width: 120 }}
        onChange={handleChange}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="disabled" disabled>
          Disabled
        </Option>
        <Option value="Yiminghe">yiminghe</Option>
      </Select>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

我的测试 …

javascript reactjs antd react-testing-library

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