我正在使用 Jest 和 react-testing-library 测试调用异步函数的组件。当我运行测试时出现错误ReferenceError: waitForElement is not defined
按照这个说明我尝试过:
withoutuseBuiltins在 中的选项.babelrc,包括@babel/polyfill在文件顶部的app.test.jsx,以及@babel/polyfill在 中的条目数组中没有的选项webpack.config.js。ReferenceError: waitForElement is not defined我从测试运行中收到错误,但应用程序编译成功
with useBuiltIns: 'entry',包括@babel/polyfill在文件顶部app.test.jsx,而 without 则@babel/polyfill位于 中的条目数组中webpack.config.js。我得到了Cannot find module 'core-js/modules/es6.array.every' from 'app.test.jsx',应用程序无法编译。
with useBuiltIns: 'entry',不包括@babel/polyfill在文件顶部app.test.jsx,并且WITH@babel/polyfill位于 中的条目数组中webpack.config.js。ReferenceError: waitForElement is not defined我从测试运行中 收到错误,并且应用程序无法编译。
这是案例 1 中的代码:
在 …
我有一个 React 组件,它允许用户向远程服务提交可能长时间运行的查询。当查询运行时,该组件会显示取消按钮。我想测试此按钮是否按预期显示,其单击处理程序是否取消之前的 API 请求,等等。
由于该按钮仅在异步 API 调用处于活动状态时才出现,因此我为此目的编写的测试在异步 API 本身的模拟实现中对按钮进行了断言。它们不是超级优雅,但我确认当我删除部分生产代码时它们确实会像我预期的那样变成红色。
在将 @testing-library/react 从 8.0.1 升级到 9.3.2 时,尽管测试仍然通过,但我现在多次收到以下警告:
console.error node_modules/@testing-library/react/dist/act-compat.js:52
Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one.
Run Code Online (Sandbox Code Playgroud)
我已在以下 CodeSandbox 中重现了该问题(请务必选择右侧的“测试”选项卡,然后查看右下角的“控制台”消息)。
关于这个GitHub 问题的最后评论说,act()只要我使用 React 测试库助手和函数(我就是这样),我就不需要担心。我缺少什么?
我想访问带有“icon”类的第一个元素。
DOM 看起来是这样的:
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/> // <== I want to access this
</div>
</div>
</div>
<div class="parent">
<div data-testid="add">
<div class="info"></div>
<div class="action">
<div class="icon"/>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如何获得第一个带有“icon”类的div?
我努力了:
const element = queryAllByTestId('add')[0].querySelector(
'div'
)[1];
Run Code Online (Sandbox Code Playgroud)
这使得元素未定义。
我已经开始在我的最新项目中使用 Next.js,我想对页面实现一些测试。我创建了一个_document文件,在其中设置了我想要使用的所有元标记,包括页面标题。
<html>
<InlineStylesHead />
<body>
<Main />
<NextScript />
<Head>
<title>testing title</title>
</Head>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
然后我设置测试来渲染此页面(应将其包含_document在其中)
它按预期工作(包括 SSR)。
然后我尝试使用react-testing-library和测试它jest
这是我的测试:
it('should render the title', () => {
render(<Page />);
waitFor(() => {
expect(document.title).toEqual('test title');
});
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,它给了我误报,而expect无论如何,block 都会给出真实的结果。我也尝试过Head直接在页面上设置,不幸的是,同样的问题。
您是否使用过任何其他技术来测试此类事物?谢谢!
reactjs jestjs next.js react-testing-library testing-library
我想测试一个使用全局fetch方法的小型 React Web 应用程序。
fetch我尝试以这种方式嘲笑:
global.fetch = jest.spyOn(global, 'fetch').mockImplementation(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
Run Code Online (Sandbox Code Playgroud)
...但是模拟似乎被忽略,而内置fetch似乎被使用:Error: connect ECONNREFUSED 127.0.0.1:80 ...看起来像是对内置的失败调用fetch。
然后我尝试使用jest.fn而不是jest.spyOn:
global.fetch = jest.fn(endpoint =>
Promise.resolve({
json: () => Promise.resolve(mockResponse)
})
);
Run Code Online (Sandbox Code Playgroud)
...并惊讶地发现了不同的错误。现在似乎已经考虑了模拟,但同时无法正常工作:
TypeError: Cannot read property 'then' of undefined
8 | this.updateTypes = this.props.updateTypes;
9 | this.updateTimeline = this.props.updateTimeline;
> 10 | fetch('/timeline/tags')
| ^
11 | .then(res => res.json())
12 | .then(tags => …Run Code Online (Sandbox Code Playgroud) 我一直在为我的alert.js 编写测试。我需要访问 prop 值来测试其严重性。我尝试了很多事情。但每次都失败了。
import React from 'react';
import PropTypes from 'prop-types';
import { Snackbar } from '@material-ui/core';
import { Alert as MuiAlert } from '@material-ui/lab';
const Alert = (props) => {
return (
<Snackbar
open={props.open}
autoHideDuration={3000}
onClose={props.onClose}
data-testid='component-alert'
>
<MuiAlert
onClose={props.onClose}
severity={props.severity}
data-testid='alert-message'
>
{props.message}
</MuiAlert>
</Snackbar>
);
};
Alert.propTypes = {
message: PropTypes.string.isRequired,
severity: PropTypes.oneOf(['error', 'warning', 'info', 'success'])
.isRequired,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
};
export default Alert;Run Code Online (Sandbox Code Playgroud)
从'@testing-library/react'导入{渲染,清理};从“../Alert”导入警报;
const mockFunc = jest.fn(); const defaultProps = { 消息:'abc',严重性:'错误',打开:true,onClose:mockFunc,};
test('render …Run Code Online (Sandbox Code Playgroud) 测试库反应未捕获“toHaveStyle”。
当我单击“内容”时,其具有blue颜色的子项更改为该red颜色。
然而,在我的测试中,它们总是有blue颜色。
我应该怎么做才能解决这个问题?
[...]
<Content data-testid={"list-element-content"} id={data.id} toggle={state[data.id - 1]}>
<div>{data.titleUnBold}</div>
<BoldTitle>{data.titleBold}</BoldTitle>
</Content>
[...]
const Content = styled.div`
color: ${ (props) => props.toggle ? "red" : "blue" };
`;
Run Code Online (Sandbox Code Playgroud)
测试代码如下:
test("color changed", () => {
const mockState = [false];
const mockSwitchGuide = jest.fn();
const { getAllByTestId, rerender } = render(
<GuideListPresenter
data={mockListData}
state={mockState}
onClick={mockSwitchGuide}
/>
);
act(() => {
fireEvent.change(getAllByTestId("list-element-content")[0],{
target: {toggle: true},
});
});
rerender(
<GuideListPresenter data={mockListData} state={mockState} onClick={mockSwitchGuide} />
);
expect(getAllByTestId("list-element-content")[0].toggle).toEqual(true); …Run Code Online (Sandbox Code Playgroud) 我是测试新手,我正在尝试使用反应测试库来测试我的应用程序。我遇到的第一个问题是测试组件内部的函数,例如事件处理程序。我发现了一些示例,其中函数(事件处理程序)作为 props 在组件中传递,但如果可能的话我不想这样做。
\n我的组件:
\nimport React, { useState } from 'react';\nimport { Redirect } from 'react-router-dom';\nimport { connect } from 'react-redux';\nimport PropTypes from 'prop-types';\n\nimport { login } from 'actions/auth';\nimport Wrapper from './styled/Wrapper';\nimport Button from './styled/Button';\nimport Title from './styled/Title';\nimport { FormWrapper, StyledForm, FormField } from './styled/Form'\nimport Input from './styled/Input';\nimport Link from './styled/Link';\n\n\nconst Login = (props) => {\n const [formData, setFormData] = useState({\n email: '',\n password: ''\n });\n\n const { email, password } = formData;\n\n const onChange = e => …Run Code Online (Sandbox Code Playgroud) 简单的测试用例:想要查看给定元素是否获得焦点。
要检查某个元素是否专注于带有 RTL 和 jest 的 React Web 应用程序,您有两个简单的选项可供选择:
expect(<element>).toHaveFocus()我不确定 React Native 的等效检查是什么(相当于 jest-dom 扩展的 RN 是https://github.com/testing-library/jest-native并且明显缺少toHaveFocus匹配器)。
javascript reactjs react-native react-testing-library react-native-testing-library
在过去,我和我的同事通常会为主父组件编写 React 测试库 (RTL) 测试,这些父组件通常有许多嵌套的子组件。该测试很有意义并且效果良好。顺便说一句,所讨论的子组件非常专用于该父组件,而不是可重用的组件。
但现在我们正在尝试为每个组件编写 RTL 测试。今天我试图为一个Alerts组件构建测试,该组件是一个组件的父组件Alert,比顶级组件低大约 4 级。这是我的测试文件中的一些示例代码:
function renderDom(component, store) {
return {
...render(<Provider store={store}>{component}</Provider>),
store,
};
}
let store = configureStore(_initialState);
const spy = jest.spyOn(store, 'dispatch');
const { queryByTestId, queryByText, debug } = renderDom(
<Alerts question={store.getState().pageBuilder.userForm.steps[0].tasks[0].questions[1]} />,
store
);
Run Code Online (Sandbox Code Playgroud)
然后我开始编写典型的 RTL 代码以使Alerts组件完成其任务。其中之一是单击将触发ADD_ALERT操作的按钮。我单步执行了所有代码,Redux 减速器显然在新警报下正常工作,正如我所预期的那样,但回到组件中Alerts,它question.alerts仍然存在null,而在生产代码中,它肯定是在新警报下正确更新的。
我与一位同事交谈,他说对于这种类型的测试,我需要人为地重新渲染组件,如下所示:
rerender(<Provider store={store}><Alerts question={store.getState().pageBuilder.userForm.steps[0].tasks[0].questions[1]} /></Provider>);
Run Code Online (Sandbox Code Playgroud)
我尝试了这个,这似乎是一个解决方案。我不完全理解为什么我必须这样做,并认为我应该联系社区,看看是否有一种方法可以避免使用rerender.
reactjs ×9
jestjs ×4
javascript ×2
unit-testing ×2
babeljs ×1
fetch ×1
next.js ×1
react-native ×1
react-native-testing-library ×1
redux ×1