我正在尝试测试当用户将文本输入到 a 时input, a会从button变为。它显然可以在浏览器中运行,但我无法通过测试。我正在使用和。但是,如果我使用本机而不是s ,测试就会通过。disabledenabledredux-formreact-testing-libraryinputredux-formField
我用最少的代码创建了一个存储库来复制问题。
测试依赖于条件渲染初始状态的组件的方法是什么?
例如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)
但是由于条件渲染,我收到此错误 …
例如,我想知道已经调度了什么以及参数。动作创建者是异步的,但我不关心它的实现,我只想知道组件是否使用正确的参数调度正确的动作创建者。我尝试过这种方法:
store.dispatch = jest.fn()
Run Code Online (Sandbox Code Playgroud)
但我无法获得任何有用的信息:
我尝试通过这种方式解决问题:
expect(store.dispatch.mock.calls[0].toString()).toBe(requestArticles().toString())
Run Code Online (Sandbox Code Playgroud)
但我不知道这个论点,但我确信有更好的方法来做到这一点。另外值得注意的是,我正在使用react-testing-library,所以我不能使用wrapper.instance().propsEnzyme。
如果这是一个重复的问题,我很抱歉。我在其他任何地方都找不到答案。
成分:
<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
我正在使用 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) 我有一些代码,在一个钩子中,来检测浏览器是否在线/离线:
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
我有一个计数器(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
到目前为止,在我正在处理的项目中,我通常对我的组件进行快照测试,这些组件以这种方式进行异步数据加载:
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)
它可以工作,但生成的快照仅包含组件的初始状态(在本例中为“加载”)。
在这种情况下,您将如何有效地对异步加载数据的组件进行快照测试?
我有一个带有某种形式的屏幕,在提交时,我使用 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 …
我正在运行一些 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 ×10
jestjs ×5
javascript ×2
redux ×2
forms ×1
react-hooks ×1
react-hooks-testing-library ×1
recoiljs ×1
redux-form ×1
setinterval ×1
testing ×1
unit-testing ×1