标签: react-testing-library

如何使用 Jest 测试 nextjs 中的 api 路由

我的 api 文件夹中有一个函数,可以搜索一组服务并根据 slug 返回单个服务。

api函数是:

import {services} from '../../../public/data/service.js'

export default async function getSingleService (req, res) {
    const serviceId = req.query.serviceID
    const result = services.filter((each) => each.url === serviceId )
    if(result.length > 0) {
        return res.status(200).json(result[0])
    } else {
        res.status(404).json({message: 'Service not found'})
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何为这个函数编写测试?我刚开始开玩笑,任何帮助都会很好。

jestjs next.js react-testing-library

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

如何在反应测试库中模拟视频持续时间?

如何使用loadedMetadata反应测试库模拟火灾事件的视频持续时间?

在我的 React 代码中,我使用 returnedMetaData 事件侦听器检索视频持续时间:

const MyVideo = () => {
   const [videoDuration, setVideoDuration] = useState(0);

   const handleMetadataLoaded = e => {
      setVideoDuration(e.currentTarget.duration);
   }

   return (
      <video
         data-testid="vidMyVideo"
         src="*some_source*"
         poster="*poster_image*"
         onLoadedMetadata={handleMetadataLoaded}
      />

   );

}
Run Code Online (Sandbox Code Playgroud)

我尝试对上面的代码进行单元测试:

import '@testing-library/jest-dom/extend-expect';
import { act, fireEvent, render } from '@testing-library/react';

...

const MyVideo = require('../').default;
const { findByTestId } = render(
   <MyVideo />
);
const inlineVideo = await findByTestId('vidMyVideo');
// the event is fired but I got NaN for the duration. how …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

当我使用 useSelector 时,React 测试库无法工作

我有一个带有 Redux 的组件useSelector,当我想测试渲染文本时,它会显示错误消息useSelector并带有错误消息:could not find react-redux context value; please ensure the component is wrapped in a <Provider>。我已放入<Provider>顶级组件,我的测试代码中的错误部分在哪里?应用程序本身运行正确。

顶级组件:

import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { Provider } from "react-redux"
import store from "./redux/store"

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("test")
)
Run Code Online (Sandbox Code Playgroud)

应用程序.js

import { useEffect, useState, useCallback } from "react"
import { useDispatch, useSelector } from "react-redux"
import { fetchPosts, showName } from "./redux/actions/posts"
import …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs babeljs redux react-testing-library

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

如何测试使用 React 测试库更改的 url 搜索?

我有一个对 url 搜索更改做出反应的组件,以及一个更改 url 搜索的按钮。我想测试当我单击按钮时,组件会做出相应的反应。这是一个codesandbox:https ://codesandbox.io/s/react-testing-library-url-change-test-b5zq1 。

应用程序.js

export default function App() {
  const [urlChanged, setUrlChanged] = useState(false);
  const handleURLSearchChange = () => {
    window.location.search = new URLSearchParams({ foo: "bar" });
  };
  useEffect(() => {
    if (window.location.search.length !== 0) {
      setUrlChanged(true);
    }
  }, []);
  return (
    <div>
      <button aria-label="change" onClick={handleURLSearchChange}>
        Change URL search
      </button>
      <p aria-label="URL Status">{urlChanged ? "Changed!" : "Not yet"}</p>
    </div>
  );
}

Run Code Online (Sandbox Code Playgroud)

应用程序规范.js

describe("App", () => {
  it("Reacts to url changes when touching the button", async …
Run Code Online (Sandbox Code Playgroud)

mocking jsdom reactjs jestjs react-testing-library

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

使用 React 测试库或 Jest 测试依赖于 Context 的组件

我的所有组件都从上下文获取数据和方法。我想测试 - 至少 - “组件渲染”案例,但是当然,当我尝试在测试案例中渲染组件时,它无法找到来自上下文的方法/函数和数据。我找不到使用 React 测试库或 Jest 将上下文值传递给测试用例的方法(我需要使用这些库,没有酶)

假设我想测试一个简单的过滤器组件。

上下文(我猜是原始用法)

import { useState, useEffect, createContext } from "react";

const Context = createContext();

const ContextProvider = ({ children }) => {
  const [books, setBooks] = useState([]);
  // other data and method code..

  const handleFilter = (value) => {
    const filteredBooks = [...books];
    if (books.length > 0) {
      switch (value) {
        case "alphabetical":
          filteredBooks.sort((a, b) => a.title - b.title);
          setBooks(filteredBooks);
          break;
        case "publishdate":
          filteredBooks.sort(
            (a, b) => b.first_publish_year - a.first_publish_year
          ); …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

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

如何使用 React 测试库和 Jest 测试必填输入字段?

我尝试通过测试弹出窗口的存在来使用 React 测试库和 Jest 来测试必需的输入字段,但失败了。我尝试了几种变体,但没有一个有效。UI 的步骤如下:

  1. 单击空白字段 清空选择字段
  2. 单击字段旁边(模糊)
  3. 将鼠标悬停在字段上
  4. 获取所需消息所需消息

实现这一点的测试代码是:

  const input = screen.getByRole('textbox', {name: /name \*/i})
  expect(input).toBeTruthy();
  fireEvent.click(input);
  fireEvent.blur(input);
  await waitFor(() => expect(input).toHaveValue(config.EMPTY_STRING));

  act(() => {
    fireEvent.mouseOver(input);
  });

  await waitFor(() => {
    expect(screen.getByText('Name is required')).toBeTruthy();
  });
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用,我收到此错误: TestingLibraryElementError:无法找到带有文本的元素:名称是必需的。这可能是因为文本被多个元素分解。在这种情况下,您可以为文本匹配器提供一个函数,以使您的匹配器更加灵活。

我这样改变了最后一行: expect(screen.getByText('Name is required')).toBeInTheDocument();但得到了同样的错误。

我尝试过 expect(screen.findByText('Name is required')).toBeInTheDocument();但遇到了同样的错误。

我的最后一次尝试是:expect(screen.findByText('Name is required')).toBeTruthy();。这里,现场测试通过了,但整体测试失败了。我得到的错误是:console.error 警告:您似乎有重叠的 act() 调用,这是不支持的。在进行新的调用之前,请务必等待之前的 act() 调用。错误:未捕获 [TypeError:无法读取 null 的属性“useRealTimers”]

所以我被困住了。任何帮助将非常感激。多谢!

reactjs jestjs react-testing-library

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

如何在 React 测试库中全局设置 waitFor 选项?

我正在查看waitFor 文档,我想知道是否有任何方法可以全局配置它,例如在jest.config用于启动测试套件的命令中?

我需要在每次测试中增加超时,这有点烦人。

reactjs jestjs react-testing-library

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

尝试使用 React 测试库检查不存在的元素总是失败

我有一个组件,在某些情况下不应该渲染任何内容(它只是返回null)。它看起来像这样:

const MyComponent = ({ renderNothing }) => {
    if (renderNothing) {
        return null
    }
    return <div data-testid='my-component'>Stuff</div>
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下,当事实renderNothing为真时,具有 data-testid 的元素my-component不存在。我当前的测试看起来像这样:


  it.only('should not render MyComponent when renderNothing is true ', async () => {
    render(<MyComponent renderNothing={true}/>)
    const myComponent = screen.getByTestId('my-component')
    expect(myComponent).not.toBeInTheDocument()
  });
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个测试总是失败并显示以下消息:

TestingLibraryElementError:无法通过以下方式找到元素:[data-testid =“my-component”]

有没有办法在不触发错误的情况下成功执行此检查?

javascript reactjs jestjs react-testing-library

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

不使用 testid 测试 Material ui Select 组件

我目前正在表单上使用 Material UI 和 React-testing-library。我有一个由对象数组填充的选择。

import React, { useState } from 'react';
import { Select, MenuItem, FormControl, InputLabel } from '@material-ui/core';

const options = [
  {
    label: 'Example 1',
    value: 123456789,
  },
  {
    label: 'Example 2',
    value: 987654321,
  },
];

const SelectTesting = () => {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <FormControl variant="outlined" fullWidth>
      <InputLabel id="selectedOptionLabel">Select an Option</InputLabel>
      <Select
        labelId="selectedOptionLabel"
        id="selectedOption"
        value={value}
        onChange={handleChange}
        label="Select an Option"
      >
        {options.map((option) => ( …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs material-ui react-testing-library

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

如何在测试中触发useLayoutEffect?(使用 Jest 和反应测试库)

我\xc2\xb4m正在开发一个小组件,该组件根据屏幕的大小更改一个标签。I\xc2\xb4m 使用 useLayoutEffect() 观察屏幕尺寸并在达到某个限制时更改标签。

\n
import React, { useLayoutEffect, useState } from 'react';\n\nconst minimumWidth = 768;\n\nconst MyComponent = () => {\n   const [label, setLabel] = useState('LABEL');\n\n   useLayoutEffect(() => {\n      const RO = new ResizeObserver((e) => {\n      if (e[0].target.clientWidth < minimumWidth) {\n        setLabel('LABEL');\n      } else {\n        setLabel('LA');\n      }\n   });\n\n   RO.observe(document.body);\n\n   return () => RO.disconnect();\n   }, []);\n\n   return (\n     <div data-testid="label_container">\n       {label}\n    </div>\n   );\n};\n\nexport default MyComponent;\n
Run Code Online (Sandbox Code Playgroud)\n

现在我需要进行测试来触发屏幕大小的调整并期望标签发生变化。但我无法触发使用布局效果。\n已经尝试过这个:

\n
import React from 'react';\nimport { render, screen } from '@testing-library/react';\n\nimport MyComponent from './MyComponent';\n\ndescribe('MyComponent', …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library react-hooks

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