我在带有 Vitest 的 React 应用程序中有以下文件(它具有与 Jest 相同的 API):
// hooks/useEntities/useEntities.ts
return useEntities() {
// this hooks send api requests so I will mock it in the test file.
}
Run Code Online (Sandbox Code Playgroud)
// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'
function SomeComponent () {
const entities = useEntities()
return <div>...</div>
}
Run Code Online (Sandbox Code Playgroud)
// SomeComponent.test.tsx
vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
default: [...]
}))
describe(...) {
it(...) {
render(<SomeComponent />)
}
}
Run Code Online (Sandbox Code Playgroud)
因为我用这种方式模拟了很多钩子。我想将模拟部分分离到不同的文件中,以便可以重复使用。我尝试过以下方法但没有成功:
// init.ts
vi.mock('hooks/useEntities/useEntities', () => ({
default: [...]
}))
Run Code Online (Sandbox Code Playgroud)
// …Run Code Online (Sandbox Code Playgroud) 我使用 React 和 Nest 创建了一个小型应用程序,以了解 WebScoket api。不仅仅是浪费时间,我想将其包装为可部署的应用程序,并将其托管在某个地方。
代码在这里: https: //github.com/An1mus/chitchat
在添加一些基本工作流程时,我遇到了以下错误的问题,该错误在运行测试后出现(测试用例通过):
/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628
setImmediate(function() { self["on" + event]() })
^
ReferenceError: setImmediate is not defined
at XMLHttpRequest.dispatchEvent (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:628:9)
at setState (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:654:12)
at XMLHttpRequest.handleError (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:572:5)
at ClientRequest.errorHandler (/Users/andrewpetrov/Projects/an1mus/chitchat/client/node_modules/.pnpm/xmlhttprequest-ssl@2.0.0/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js:490:14)
at ClientRequest.emit (node:events:527:28)
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Run Code Online (Sandbox Code Playgroud)
由于某种原因,当我运行测试时它会触发,即使我唯一的测试是这样的:
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders the app', async () => {
// this is a …Run Code Online (Sandbox Code Playgroud) 我正在使用 React 测试库测试表单中的多个无线电输入。他们中的大多数都有是/否的标签,所以我不能使用findByLabelText. 我收到的完整错误是:Found a label with the text of: yes, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly. 。
这是我失败的测试之一:
test('Sealing Properly radio input should exist, be unchecked, and be clickable', async () => {
render(
<Component />
);
const sealingProperlyRadioGroup = await screen.findByTestId('sealingProperly');
const sealingProperlyRadio = await within(sealingProperlyRadioGroup).findByLabelText('yes');
expect(sealingProperlyRadio).toBeInTheDocument();
expect(sealingProperlyRadio).not.toBeChecked();
fireEvent.click(sealingProperlyRadio)
expect(sealingProperlyRadio).toBeChecked();
});
Run Code Online (Sandbox Code Playgroud)
这是错误后输出的 html:
<div
class="radioGroup mb-3"
data-testid="sealingProperly"
>
<label
class="radio" …Run Code Online (Sandbox Code Playgroud) 我有一个生成警告的测试An update to DropDownMultiPick inside a test was not wrapped in act(...)
警告指向这段代码:
10 | const toggleDropdown = () => {
> 11 | setIsOpen(!isOpen);
| ^
12 | };
Run Code Online (Sandbox Code Playgroud)
const DropDownMultiPick = ({ title, options, selectedOptions, handleOptionsChange }) => {
const [isOpen, setIsOpen] = useState(false);
const [tempSelectedOptions, setTempSelectedOptions] = useState([...selectedOptions]);
const toggleDropdown = () => {
setIsOpen(!isOpen);
};
...
Run Code Online (Sandbox Code Playgroud)
const title = "Test Options";
const options = ["Option 1", "Option 2", "Option 3"];
const selectedOptions = …Run Code Online (Sandbox Code Playgroud) 我在测试React使用的组件时遇到了麻烦react-loadable。说,我有一个Button组件,取决于它是否接收icon道具,它会Icon像这样加载一个组件:
Button.js
const LoadableIcon = Loadable({
loader: () => import('./Icon'),
loading: () => <div>Loading...</div>
})
function Button(props) {
return (
<button
onClick={props.onClick}>
{props.icon &&
<LoadableIcon name={props.icon} />}
{props.children}
</button>
)
}
Run Code Online (Sandbox Code Playgroud)
但是,当我测试该组件时,Icon尚未加载,而是测试仅找到了<div>Loading...</div>元素...
Button.test.js
import React from 'react'
import {render} from 'react-testing-library'
import Button from '../Button'
describe('Button', () => {
it('renders icon correctly', () => {
const {getByText} = render(
<Button
icon='add'
/>
)
expect(getByText('add')).toBeInTheDocument()
})
}) …Run Code Online (Sandbox Code Playgroud) 我目前正在使用Jest&react-testing-library测试输入。我试图测试每当输入字段更改时onChange函数是否会触发。这是我的代码示例:
const placeHolder = 'first name';
const onChange = jest.fn();
test('<InputText/>', () => {
const {getByPlaceholderText} = render(
<InputText placeholder={placeHolder} onChange={onChange} />
);
const input = getByPlaceholderText(placeHolder);
fireEvent.change(input, {
target: {value: 'pls work'},
});
expect(onChange).toHaveBeenCalledTimes(1);
});
Run Code Online (Sandbox Code Playgroud)
这是运行此测试时在终端上获得的东西:
expect(jest.fn()).toHaveBeenCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times.
Run Code Online (Sandbox Code Playgroud)
我在其他测试中使用了fireEvent.click()函数,但没有任何问题,但是fireEvent.change()似乎对我不起作用。
我正在尝试测试组件是否由于输入元素的变化而更新。我使用fireEvent.change()-function,然后如果我检查使用getByPlaceholderText它发现的节点的值已按预期进行了更新。但是我看不到react组件本身的变化。
这可能是因为更改直到重新渲染才发生。我将如何测试呢?react-testing-library rerender似乎是“从头开始”启动组件(即没有新的输入值),却waitForElement从不找到它在等待什么。
这是组件TestForm.js:
import React from 'react';
import { withState } from 'recompose';
const initialInputValue = 'initialInputValue';
const TestForm = ({ inputValue, setInputValue }) => (
<>
{console.log('inputValue', inputValue)}
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="placeholder" />
{inputValue !== initialInputValue && <div>Input has changed</div>}
</>
);
export default withState('inputValue', 'setInputValue', initialInputValue)(TestForm);
Run Code Online (Sandbox Code Playgroud)
这是测试,使用npx jest test.js以下命令运行:
import React from 'react';
import { cleanup, fireEvent, render, waitForElement } from 'react-testing-library';
import TestForm from './TestForm'; …Run Code Online (Sandbox Code Playgroud) 我正在使用react-testing-library。在文件中说
请注意,将其用作通过类或ID查询的转义填充是一种不好的做法,因为用户无法看到或识别这些属性。如果需要,请使用一个testid。
我想知道为什么这是不好的做法。我不想用data-testid乱丢我的代码。我的组件中已经有ID和className。为什么不建议使用它们?
谢谢。
我正在开玩笑,并react-testing-library为我的应用程序提供单元测试范围。
我使用了这个方便的辅助函数Kent C. Dodds在他的一个视频中展示了它:
const renderWithRedux = ui => ({
...render(<Provider store={store}>{ui}</Provider>),
store,
});
Run Code Online (Sandbox Code Playgroud)
我在测试连接的组件时使用。
我遇到一个问题,为了渲染组件,我需要获取一些数据以准确地解决测试问题,或者至少将模拟数据注入存储中。我没有这样做
这是我的测试:
test('navbar accepts props', async () => {
/**
* Something I was testing
*/
const functionToTest = () => async dispatch => {
dispatch(fetchTickets());
};
functionToTest();
const isReady = true;
const mockData = {
sessionInformation: {
ticket: { label: 'Total Tickets' },
sessionDuration: { sessionLabel: 'Session Duration', duration: 42 },
equipment: { type: 'Desktop', operatingSystem: 'Windows' },
},
component: { isReady …Run Code Online (Sandbox Code Playgroud) 我有一个React组件,它会生成一个按钮,其中的内容包含<span>类似这样的元素:
function Click(props) {
return (
<button disable={props.disable}>
<span>Click me</span>
</button>
);
}
Run Code Online (Sandbox Code Playgroud)
我想使用react-testing-library和mocha+ 测试该组件的逻辑chai。
我目前遇到的问题是getByText("Click me")选择器返回<span>DOM节点,但是对于测试,我需要检查disable该<button>节点的属性。处理此类测试用例的最佳实践是什么?我看到了一些解决方案,但是所有这些听起来都有些偏离:
data-test-id的<button>元素<Click />组件的祖先之一,然后选择within(...)此范围的按钮fireEvent并检查没有任何反应您可以提出更好的方法吗?