我正在尝试模拟将数据检索到组件的fetch()。
我正在使用它作为模拟提取的模型,但是我无法使其正常工作。
运行测试时出现此错误: babel-plugin-jest-hoist: The module factory of 'jest.mock()' is not allowed to reference any out-of-scope variables.
有没有办法让这些函数返回模拟数据,而不是实际尝试进行真正的API调用?
返回角色映射到每个用户的用户。
const getUsersWithRoles = rolesList =>
fetch(`/users`, {
credentials: "include"
}).then(response =>
response.json().then(d => {
const newUsersWithRoles = d.result.map(user => ({
...user,
roles: rolesList.filter(role => user.roles.indexOf(role.iden) !== -1)
}));
return newUsersWithRoles;
})
);
Run Code Online (Sandbox Code Playgroud)
const UserTable = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
getTableData();
}, []);
const getTableData = () => { …Run Code Online (Sandbox Code Playgroud) 我正在使用 create-react-app、Jest 和 react-testing-library 来配置聊天机器人项目。
例如,我有一个连接到 WebSocket 服务器的 React 功能组件,并且 DOM 会根据 WebSocket 消息进行更改
const LiveChat = () => {
const [socket, setSocket] = useState(null)
useEffect(() => {
setSocket(new WebSocket('ws://localhost:1234'))
}, [])
useEffect(() => {
socket && socket.onmessage = message => { handleAgentMessages(message.data) }
}, [socket])
const handleAgentMessages = message => {
const { messageContent, messageType, secureKey } = JSON.parse(message)
if (messageType === TEXT && messageContent) {
alert(messageContent)
playChatMessageSound()
}
...
}
return (
<div className='live-chat' data-testid='live-chat'>
...
</div>
) …Run Code Online (Sandbox Code Playgroud) 我试图只使用waitForElementToBeRemoved一个元素,但 Jest 超时了。当我传入一个函数时,它起作用了。
我对这个功能的理解是它应该能够采用一个元素:https : //github.com/testing-library/dom-testing-library/pull/460
我验证了我的应用程序正在使用@testing-library/dom@7.8.0。
这是代码:
// doesn't work
await waitForElementToBeRemoved(screen.getByText("Loading..."));
// works
await waitForElementToBeRemoved(() => screen.getByText("Loading..."));
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
这是我的测试用例的样子:
const renderCard = ({
onSubmit = jest.fn(),
}: RenderCardParams = {}) => {
return render(
<Card title={title} onSubmit={onSubmit}>
<Button type="submit">Save</Button>
</Card>,
);
};
it("should invoke onSubmit when form is submitted", async () => {
const onSubmit = jest.fn();
window.HTMLFormElement.prototype.submit = () => {};
const { getByText } = renderCard({ onSubmit });
const button = getByText("Save").closest("button");
if (button) {
fireEvent.click(button);
}
await wait(() => expect(onSubmit).toHaveBeenCalled());
});
Run Code Online (Sandbox Code Playgroud)
我收到“错误:未实现:HTMLFormElement.prototype.submit”。我尝试了这里提到的解决方案https://github.com/jsdom/jsdom/issues/1937,但没有奏效。我不想消除错误而是正确执行测试。谢谢你。
我的文本输入是
<TextField
className={classes.textField}
data-testid={name}
variant="outlined"
error={false}
required
onChange={element => {
if (onTextChange) {
onTextChange(name, element.target.value);
}
}}
disabled={!editEnable}
name={name}
label={label}
defaultValue={values}
fullWidth
/>
Run Code Online (Sandbox Code Playgroud)
和 UI 在此处输入图像描述
如何在反应测试库中更改此文本元素的值?
我正在学习有关反应测试的教程。本教程有一个像这样的简单组件来显示测试异步操作:
import React from 'react'
const TestAsync = () => {
const [counter, setCounter] = React.useState(0)
const delayCount = () => (
setTimeout(() => {
setCounter(counter + 1)
}, 500)
)
return (
<>
<h1 data-testid="counter">{ counter }</h1>
<button data-testid="button-up" onClick={delayCount}> Up</button>
<button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
</>
)
}
export default TestAsync
Run Code Online (Sandbox Code Playgroud)
而测试文件是这样的:
import React from 'react';
import { render, cleanup, fireEvent, waitForElement } from '@testing-library/react';
import TestAsync from './TestAsync'
afterEach(cleanup);
it('increments counter after 0.5s', …Run Code Online (Sandbox Code Playgroud) 我有这个组件:
import React, { lazy, Suspense } from 'react';
import { ErrorBoundary } from '../ErrorBoundary';
const FALLBACK = <svg aria-label="" data-testid="icon-fallback" viewBox="0 0 21 21" />;
const ERROR = (
<svg data-testid="icon-notdef" viewBox="0 0 21 21">
<path d="M0.5,0.5v20h20v-20H0.5z M9.1,10.5l-6.6,6.6V3.9L9.1,10.5z M3.9,2.5h13.2l-6.6,6.6L3.9,2.5z M10.5,11.9l6.6,6.6H3.9 L10.5,11.9z M11.9,10.5l6.6-6.6v13.2L11.9,10.5z" />
</svg>
);
export const Icon = ({ ariaLabel, ariaHidden, name, size }) => {
const LazyIcon = lazy(() => import(`../../assets/icons/${size}/${name}.svg`));
return (
<i aria-hidden={ ariaHidden }>
<ErrorBoundary fallback={ ERROR }>
<Suspense fallback={ FALLBACK }>
<LazyIcon aria-label={ …Run Code Online (Sandbox Code Playgroud) javascript reactjs jestjs react-testing-library react-error-boundary
运行 React 测试库以在使用 Emotion css 属性的 JSX 上生成快照,导致没有渲染任何 CSS。
我试过使用“@emotion/jest/serializer”,但仍然没有运气。
成分:
<button
role="button"
css={(theme)=> {
backgroundColor: 'hotpink',
'&:hover': {
color: theme('lightgreen'),
},
}}
/>
Run Code Online (Sandbox Code Playgroud)
测试:
import React from 'react';
import { render } from '@testing-library/react';
import { createSerializer } from '@emotion/jest';
import { Component } from './component';
expect.addSnapshotSerializer(createSerializer());
describe('IconComponent', () => {
it('should match the snapshot for the given props', () => {
const { asFragment } = render(<Component icon="knownIcon" />);
expect(asFragment()).toMatchSnapshot();
});
Run Code Online (Sandbox Code Playgroud)
快照:( 这被呈现为匿名对象而不是 CSS)
exports[` 1`] = ` …Run Code Online (Sandbox Code Playgroud) 好的,我有一个需要at-least10 个字符的输入字段,它启用了显示 的按钮Save & Next。
如果description.length < 10,则它保持禁用状态。这在用户界面中运行良好。\n但我无法为其编写测试。
test(\' Disables the save and next button if description < 10\', () => {\n render(<StepOne />, { initialState });\n const input = screen.getByLabelText(/description/i);\n fireEvent.change(input, { target: { value: \'123456\' } }); // Length < 10\n const button = screen.getByText(\'Save & Next\');\n console.log(button.innerHTML);\n expect(button).toBeDisabled(true);\n });\nRun Code Online (Sandbox Code Playgroud)\n错误:
\nexpect(element).toBeDisabled()\n\n \xe2\x9d\x8c Received element is not disabled:\n <span class="MuiButton-label" />\nRun Code Online (Sandbox Code Playgroud)\n我想知道我在这里缺少什么
\n我有一个使用Formik制作的基本登录表单,只是尝试编写 RTL 和 jest 代码来填写详细信息、提交表单并导航到主页。因此,写了以下内容:
it('Fill the form and login', async () => {
render(<Login />)
await userEvent.type(screen.getByTestId('emailInput'), 'neeraj@gmail.com')
await userEvent.type(screen.getByTestId('passwordInput'), 'neeraj')
await userEvent.click(screen.getByTestId('submitBtn'))
expect(window.location.pathname).toBe('/')
})
Run Code Online (Sandbox Code Playgroud)
上面的测试已经通过,但出现了经典的行为错误。
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
Run Code Online (Sandbox Code Playgroud)
因此,参考此博客文章并按照建议使用waitForElementToBeRemoved函数,但现在测试因超时错误而失败。
使用 waitForElementToBeRemoved 更新测试用例
When testing, code that causes React state updates should …Run Code Online (Sandbox Code Playgroud) reactjs ×8
jestjs ×5
javascript ×3
emotion ×1
forms ×1
mocking ×1
react-hooks ×1
typescript ×1
unit-testing ×1
websocket ×1