标签: react-testing-library

在 redux-form 上使用 React-testing-library 时,表单输入不会改变

我正在尝试测试当用户将文本输入到 a 时input, a会从button变为。它显然可以在浏览器中运行,但我无法通过测试。我正在使用和。但是,如果我使用本机而不是s ,测试就会通过。disabledenabledredux-formreact-testing-libraryinputredux-formField

我用最少的代码创建了一个存储库来复制问题。

forms reactjs redux redux-form react-testing-library

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

使用反应测试库测试依赖于状态的条件渲染

测试依赖于条件渲染初始状态的组件的方法是什么?

例如showLessFlag依赖于状态,在 react-testing-library 中测试状态会适得其反。

那么我将如何在CommentList组件中测试这种情况

{showLessFlag === true ? (
    // will show most recent comments below
    showMoreComments()
) : (
    <Fragment>
        {/* filter based on first comment, this shows by default */}
        {filterComments.map((comment, i) => (
            <div key={i} className="comment">
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ))}
    </Fragment>
)}
Run Code Online (Sandbox Code Playgroud)

应该像下面这样测试

  it("should check more comments", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-show-more");
        expect(commentList).toBeNull();
    });
Run Code Online (Sandbox Code Playgroud)

但是由于条件渲染,我收到此错误 …

reactjs react-testing-library

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

如何使用 jest.fn() 模拟调度

例如,我想知道已经调度了什么以及参数。动作创建者是异步的,但我不关心它的实现,我只想知道组件是否使用正确的参数调度正确的动作创建者。我尝试过这种方法:

store.dispatch = jest.fn()
Run Code Online (Sandbox Code Playgroud)

但我无法获得任何有用的信息:

这是我可以从 store.dispatch.mock 得到的

我尝试通过这种方式解决问题:

expect(store.dispatch.mock.calls[0].toString()).toBe(requestArticles().toString())
Run Code Online (Sandbox Code Playgroud)

但我不知道这个论点,但我确信有更好的方法来做到这一点。另外值得注意的是,我正在使用react-testing-library,所以我不能使用wrapper.instance().propsEnzyme。

javascript reactjs jestjs react-testing-library

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

无法在具有特定名称的列表项上使用 getByRole - RTL

如果这是一个重复的问题,我很抱歉。我在其他任何地方都找不到答案。

成分:

<ul>
  <li>Pending tasks</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

测试代码:

expect(getByRole("listitem", { name: "Pending tasks" })).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)

错误:

TestingLibraryElementError: Unable to find an accessible element with the role "listitem" and name "Pending tasks"
Run Code Online (Sandbox Code Playgroud)

这是重现此内容的代码和框链接:https ://codesandbox.io/s/wandering-browser-mrf78?file =/ src/App.test.js

即使它显示错误提示无法找到,它仍然建议我将 li 和 ul 标记作为可用角色。

Here are the accessible roles:
 --------------------------------------------------
  list:

  Name "":
  <ul />

  --------------------------------------------------
  listitem:

  Name "":
  <li />

Run Code Online (Sandbox Code Playgroud)

有人可以解释一下我在这里缺少什么吗?我尝试使用正则表达式匹配器,但没有运气。

testing reactjs jestjs react-testing-library testing-library

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

React 测试库不变性失败:您不应在 &lt;Router&gt; 之外使用 &lt;Route&gt;

我正在使用 React 测试库测试我的组件是否成功地使用 Redux 呈现。我的实用程序组件无法通过 renderWithRedux 测试。这是我的 App 组件。

function App() {
return (
    <>
        <Router>
            <NavBar />
            <div className="container">
                <Switch>
                    <Route exact path='/' component={Home}/>
                    <AuthRoute exact path='/login' component={Login} />
                    <AuthRoute exact path='/signup' component={Signup} />
                    <Route exact path='/users/:handle' component={UserProfile} />
                    <Route exact path='/users/:handle/post/:postId' component={UserProfile} />
                </Switch>
            </div>
        </Router>
    </>
);
Run Code Online (Sandbox Code Playgroud)

}

这是我的 AuthRoute 实用程序组件。

const AuthRoute = ({ component: Component, authenticated, ...rest }) => (
      // if authenticated, redirect to homepage, otherwise redirect to signup or login
        <Route
        {...rest}
        render={(props) …
Run Code Online (Sandbox Code Playgroud)

reactjs redux react-testing-library

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

如何触发事件 React 测试库

我有一些代码,在一个钩子中,来检测浏览器是否在线/离线:

export function useConnectivity() {
  const [isOnline, setNetwork] = useState(window.navigator.onLine);
  const updateNetwork = () => {
    setNetwork(window.navigator.onLine);
  };
  useEffect(() => {
    window.addEventListener('offline', updateNetwork);
    window.addEventListener('online', updateNetwork);
    return () => {
      window.removeEventListener('offline', updateNetwork);
      window.removeEventListener('online', updateNetwork);
    };
  });
  return isOnline;
}
Run Code Online (Sandbox Code Playgroud)

我有这个基本测试:

test('hook should detect offline state', () => {
  let internetState = jest.spyOn(window.navigator, 'onLine', 'get');
  internetState.mockReturnValue(false);

  const { result } = renderHook(() => useConnectivity());
  expect(result.current.valueOf()).toBe(false);
});
Run Code Online (Sandbox Code Playgroud)

但是,我想运行一个测试,看看它在offline触发事件时是否返回正确的值,而不仅仅是在渲染时模拟返回值之后。解决这个问题的最佳方法是什么?到目前为止我得到的是这样的:

test('hook should detect offline state then online state', async () => {
  const …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library react-hooks react-hooks-testing-library

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

React 测试库:如何在文档中查找由 setInterval 更新的文本?

我有一个计数器(React hooks 组件),它每秒递增地呈现一个新数字。当钩子更新时,如何断言 DOM 中存在某个数字?

这是代码沙箱链接

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

export default function Counter() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const intervalId = setInterval(function () {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(intervalId);
  });

  return <span>{count}</span>;
}
Run Code Online (Sandbox Code Playgroud)

测试失败

  test("should be able to find 3 directly", async () => {
    render(<Counter />);

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });
Run Code Online (Sandbox Code Playgroud)

通过测试

  test("should render one and then two and then three", …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing setinterval reactjs react-testing-library

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

如何使用 react-testing-library 对执行异步数据加载的组件进行快照测试?

到目前为止,在我正在处理的项目中,我通常对我的组件进行快照测试,这些组件以这种方式进行异步数据加载:

describe('MyComponent component', () =>{
    test('Matches snapshot', async () => {
        fetch.mockResponse(JSON.stringify(catFacts));

        const { asFragment } = render(<MyComponent />);
        await waitFor(() => expect(asFragment()).toMatchSnapshot());
    })
})
Run Code Online (Sandbox Code Playgroud)

我觉得它非常方便,因为它允许有一个包含组件不同状态(加载、错误、加载数据)的快照。

问题是我刚刚发现根本不推荐这种方法,并且@testing-library/react 包的最新更新不允许我再以这种方式测试我的组件。

根据包的 eslint 规则,我必须像这样修改我的代码:

describe('MyComponent component', () =>{
    test('Matches snapshot', () => {
        fetch.mockResponse(JSON.stringify(catFacts));

        const { asFragment } = render(<MyComponent />);
        expect(asFragment()).toMatchSnapshot();
    })
})
Run Code Online (Sandbox Code Playgroud)

它可以工作,但生成的快照仅包含组件的初始状态(在本例中为“加载”)。

在这种情况下,您将如何有效地对异步加载数据的组件进行快照测试?

reactjs jestjs react-testing-library snapshot-testing

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

如何使用 jest 和 react-testing-library 测试 react-toastify

我有一个带有某种形式的屏幕,在提交时,我使用 axios 将请求发送到后端。成功收到响应后,我用 react-toastify 敬酒。非常直接的屏幕。但是,当我尝试使用 jest 和 react 测试库通过集成测试来测试这种行为时,我似乎无法让 Toast 出现在 DOM 上。

我有一个像这样的实用程序渲染器来渲染我正在使用 toast 容器测试的组件:

import {render} from "@testing-library/react";
import React from "react";
import {ToastContainer} from "react-toastify";

export const renderWithToastify = (component) => (
  render(
    <div>
      {component}
      <ToastContainer/>
    </div>
  )
);
Run Code Online (Sandbox Code Playgroud)

在测试本身中,我用 react-testing-library 填写表单,按下提交按钮,然后等待 toast 出现。我正在使用模拟服务工作者来模拟响应。我确认响应返回 OK,但由于某种原因,吐司拒绝出现。我目前的测试如下:

expect(await screen.findByRole("alert")).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)

我正在寻找具有角色警报的元素。但这似乎不起作用。另外,我尝试做这样的事情:

...

beforeAll(() => {
  jest.useFakeTimers();
}

...

it("test", () => {
  ...

  act(() =>
    jest.runAllTimers();
  )
  expect(await screen.findByRole("alert")).toBeInTheDocument();
}

Run Code Online (Sandbox Code Playgroud)

我对 JS 有点陌生,问题可能是由于 axios 和 react-toastify 的异步性质,但我不知道如何测试这种行为。我尝试了很多东西,包括模拟定时器并运行它们,模拟定时器并推进它们,而不是模拟它们并等待等等。我什至试图模拟 toast …

reactjs jestjs react-testing-library react-toastify

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

“在渲染时没有保留反冲值,或在超时后提交。这很好,但很奇怪。未定义”是什么意思?我该如何解决?

我正在运行一些 react-testing-library 测试并收到Did not retain recoil value on render, or committed after timeout elapsed. This is fine, but odd. undefined. 这是什么意思?我该如何解决?

我刚刚添加了一个新的反冲原子。

我正在使用后坐力 0.3.0。

reactjs react-testing-library recoiljs

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