标签: react-testing-library

Jest + react-testing-library:警告更新未包含在 act() 中

我正在用 react-testing-library 测试我的组件,并且测试运行良好。我只是无法摆脱这个警告,fireEvent 应该包装在开箱即用的行为中,但我试图再次包装它,但它没有帮助。

这是我的测试用例。

it.only("should start file upload if file is added to the field", async () => {
    jest.useFakeTimers();
    const { getByTestId } = wrapper;
    const file = new File(["filefilefile"], "videoFile.mxf");

    const fileInput = getByTestId("drop-zone").querySelector(
      "input[type='file']"
    );

    fireEvent.change(fileInput, { target: { files: [file] } });

    act(() => {
      jest.runAllTimers();
    });

    await wait(() => {
      expect(
        initialProps.uploadItemVideoFileConnect.calledWith(file, 123)
      ).toBe(true);
    });
  });
Run Code Online (Sandbox Code Playgroud)

这是警告

Warning: An update to UploadButtonGridComponent inside a test was not wrapped in act(...).

    When testing, code that …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-testing-library

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

如何在反应测试库中获得代码覆盖率

我已经使用 react 测试库(@testing-library/react & @testing-library/dom)和 jest-dom(@testing-library/jest-dom)编写了单元测试。我能够成功运行我的测试。

我没有使用 jest/jest-cli complete pacakge。我正在使用反应测试库和那个 jest-dom(@testing-library/jest-dom) 它可能是一些子包或我不确定到底该叫它什么的东西。

如何使用反应测试库获得代码覆盖率?

在此处输入图片说明

reactjs react-testing-library

13
推荐指数
3
解决办法
9228
查看次数

如何使用 Jest 和 react-testing-library 测试 useRef?

我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。

我有一个使用 useRef 钩子的功能组件。当一条新消息到来时,会触发 useEffect 钩子并通过查看 ref 的当前属性引起滚动事件。

const ChatBot = () => {
  const chatBotMessagesRef = useRef(null)
  const chatBotContext = useContext(ChatBotContext)
  const { chat, typing } = chatBotContext

  useEffect(() => {
    if (typeof chatMessagesRef.current.scrollTo !== 'undefined' && chat && chat.length > 0) { 
       chatBotMessagesRef.current.scrollTo({
         top: chatMessagesRef.current.scrollHeight,
         behavior: 'smooth'
       })
    }
    // eslint-disable-next-line
  }, [chat, typing])

   return (
    <>
      <ChatBotHeader />
      <div className='chatbot' ref={chatBotMessagesRef}>
        {chat && chat.map((message, index) => {
          return <ChatBotBoard answers={message.answers} key={index} currentIndex={index + …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

react-testing-library - 如何模拟文件上传到 &lt;input type="file" /&gt; 元素?

我正在使用用户事件来尝试进行更“真实”的用户交互。但是,在我单击输入后,它不会触发该onChange功能,因为默认情况下它只会为用户打开文件浏览器以上传文件。如何模拟用户上传文件?

我的代码:

// Component
const FileInputComponent = ({ handleFileUpload }) => (
  <div>
    <input type="file" id="testing" accept=".png,.jpg" onChange={handleFileUpload} />
    <label htmlFor="testing">Input File Here</label>
  </div>
);
Run Code Online (Sandbox Code Playgroud)
// Test file
test("Clicking on the label button calls the `handleFileUpload` function", () => {
  const handleFileUploadMockFn = jest.fn();
  const { getByLabelText } = render(<FileInputComponent handleFileUpload={handleFileUploadMockFn} />
  userEvent.click(getByLabelText("Input File Here"));
  expect(handleFileUploadMockFn).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)

react-testing-library

13
推荐指数
5
解决办法
7081
查看次数

如何使用反应测试库模拟反应组件?

我有一个反应组件,它有两个子组件,如下所示:

import {Child1} from './child1';
import {Child2} from './child2';
...
return (
  <>
    <Child1 />
    <Child2 />
  </>
)
Run Code Online (Sandbox Code Playgroud)

我正在使用 Reacttesting-library和创建的应用程序create react app,而不是弹出。我想在我的单元测试中模拟它们,因为它们有自己的测试,所以我试图:

jest.mock('./child1', () => 'some mocked string');
jest.mock('./child1', () => 'some mocked string');
Run Code Online (Sandbox Code Playgroud)

但是当我使用它渲染它时,import { render } from '@testing-library/react';我看到以下内容Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined

这是为什么?我如何模拟这些组件?

testing mocking reactjs jestjs react-testing-library

13
推荐指数
1
解决办法
4万
查看次数

screen.getByText 不是函数

screen > getByText/etc在我开始转向测试方式之前,我大部分时间都将 jest 与 React-testing-library 一起使用,没有出现任何问题。

测试

describe('test the dashboard when loaded', () => {
  it('is not loading', async () => {
    render(<ComponentToTest />)
    expect(screen.getByText(/loading/i)).not.toBeInTheDocument()
  })

  it('displays the case summary correctly', async () => {
    const allCasesElement = getByTestId(/Timeline/i)
    within(allCasesElement).findByText('30/12/2021')
    within(allCasesElement).findByText('12:06')
    within(allCasesElement).findByText('enums.case.VERIFICATION_GO_TO_COMPLETION')
  })
})
Run Code Online (Sandbox Code Playgroud)

失败

TS2339: Property 'getByText' does not exist on type 'Screen'.

screen.getByText is not a function
TypeError: screen.getByText is not a function
    at Object.<anonymous> (/var/www/src/pages/Application/Overview/Timeline/Timeline.test.tsx:250:19)
    at Promise.then.completed (/var/www/node_modules/jest-circus/build/utils.js:276:28)
    at new Promise (<anonymous>)
Run Code Online (Sandbox Code Playgroud)

setupTests.ts

import '@testing-library/jest-dom' …
Run Code Online (Sandbox Code Playgroud)

javascript typescript jestjs react-testing-library

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

测试库中的 getByText、findByText 和 queryByText 有什么区别?

获取元素文本内容的方法有多种:getByTextvs findByTextvs queryByText
有时我对使用哪一个感到困惑。
我在反应本机中有以下示例:

it('should render children', () => {
  const mockedChildComponentTxt = 'Children are rendered';
  const { getByText, findByText, queryByText } = render(
    <MyProvider>
      <div>{mockedChildComponentTxt}</div>
    </MyProvider>,
  );
  expect(queryByText(mockedChildComponentTxt)).toBeTruthy()
});
Run Code Online (Sandbox Code Playgroud)

queryByText虽然getByText失败了,但是findByText有效。

debug()导致:

<RNCSafeAreaView
    onInsetsChange={[Function anonymous]}
    style={
      Object {
        "flex": 1,
      }
    }
>
    <div>
      Children are rendered
    </div>
</RNCSafeAreaView>
Run Code Online (Sandbox Code Playgroud)

为什么findByText在上面的例子中可以工作,但是getByTextqueryByText失败了?

reactjs react-native react-testing-library

13
推荐指数
1
解决办法
7782
查看次数

使用 react-testing-library 进行测试时,我可以手动触发状态更改吗?

我仍在将我的 Enzyme 测试转移到 react-testing-library 的过程中,我有一个相当常见的场景,当一个组件安装时,它会启动一个 Ajax 请求来获取一些数据。就在获取开始之前,它设置一些状态值以指示它正在加载,这反过来呈现一个微调器。完成后,状态将更新为数据,并在适当的情况下将“loadingState”设置为“Completed”或“Failed”。

import React, { useEffect, useState } from "react";
import { SwapSpinner } from "react-spinners-kit";
import styled from "styled-components";
import * as R from "ramda";

import { getPeople } from "./getPeople";

const FlexCenter = styled.div`
  height: 250px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const loadingStates = {
  notStarted: "notStarted",
  isLoading: "isLoading",
  success: "success",
  failure: "failure"
};

function App() {
  const [people, setPeople] = useState([]);
  const [isLoading, setLoading] = useState(loadingStates.notStarted);

  useEffect(() => {
    setLoading(loadingStates.isLoading); …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library

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

在 react-testing-library 中按 Enter 提交表单不起作用

描述:

I am trying to test that a form submits when the user presses the "Enter" key. I have a passing test for when pressing the Submit button, but I also want to be sure the form submits with the keyboard (convenience and a11y).

Code:

test("should submit when pressing enter", () => {
  const handleSubmit = jest.fn();
  const { getByLabelText } = render(<App handleSubmit={handleSubmit} />);
  const input = getByLabelText("Name:");

  fireEvent.change(input, { target: { value: "abc" } });
  fireEvent.keyPress(input, { key: …
Run Code Online (Sandbox Code Playgroud)

forms events reactjs jestjs react-testing-library

12
推荐指数
2
解决办法
8226
查看次数

测试自定义钩子:不变违规:找不到 react-redux 上下文值;请确保组件被包裹在 &lt;Provider&gt; 中

我有一个我想测试的自定义钩子。它接收一个 redux store 调度函数并返回一个函数。为了得到结果,我正在尝试做:

const { result } = renderHook(() => { useSaveAuthenticationDataToStorages(useDispatch())});
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误:

不变违规:找不到 react-redux 上下文值;请确保组件被包裹在一个

发生这种情况是因为useDispatch没有连接商店。但是,我这里没有任何组件可以与提供程序一起包装。我只需要测试只是将数据保存到商店的钩子。

我该如何解决?

reactjs jestjs redux react-testing-library

12
推荐指数
4
解决办法
3万
查看次数