我有一个我想测试的自定义钩子。它接收一个 redux store 调度函数并返回一个函数。为了得到结果,我正在尝试做:
const { result } = renderHook(() => { useSaveAuthenticationDataToStorages(useDispatch())});
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个错误:
不变违规:找不到 react-redux 上下文值;请确保组件被包裹在一个
发生这种情况是因为useDispatch没有连接商店。但是,我这里没有任何组件可以与提供程序一起包装。我只需要测试只是将数据保存到商店的钩子。
我该如何解决?
我有一个带有表单的反应组件。我想对表单是否使用正确的数据提交进行单元测试(使用 jest 和 RTL)。这是我的组件和单元测试方法:
成分:
class AddDeviceModal extends Component {
handleOnSave(event) {
const { deviceName } = event.target;
const formData = {
deviceName: deviceName.value,
};
this.props.onSave(formData);
}
render() {
return (
<Form onSubmit={this.handleOnSave}>
<Form.Label>Device Name</Form.Label>
<Form.Control name="deviceName" placeholder="Device Name" required />
<Button type="submit">Save Device</Button>
</Form>
);
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
it("Test form submit and validation", () => {
const handleSave = jest.fn();
const props = {
onSave: handleSave,
};
render(<AddDeviceModal {...props} />);
const deviceNameInput = screen.getByPlaceholderText(/device name/i);
fireEvent.change(deviceNameInput, { target: { …Run Code Online (Sandbox Code Playgroud) 我想使用反应测试库获取 span 元素的值。
我想做什么?
我有一个如下所示的 span 元素,显示一些值
render = () => {
const count = 2;
return (
<span data-test-id="test-span">
{count}
</span>
)
}
Run Code Online (Sandbox Code Playgroud)
现在在我的测试中我访问如下元素,
const span_element = getByTestId('test-span');
Run Code Online (Sandbox Code Playgroud)
但我不知道如何检索它的价值。
我尝试使用 span_element.value 但说“HTMLElement 上不存在属性值”
我怎样才能解决这个问题。有人可以帮我解决这个问题吗?谢谢。
我被困在这里进行一个测试,我想验证在滚动浏览由react-window导入的列表组件后,正在渲染不同的项目。该列表位于一个表格组件内,该组件保存了 React 上下文中的滚动位置,这就是我需要测试整个表格组件的原因。
不幸的是,滚动事件似乎没有效果,列表仍然显示相同的项目。
测试看起来像这样:
render(
<SomeProvider>
<Table />
</SomeProvider>
)
describe('Table', () => {
it('scrolls and renders different items', () => {
const table = screen.getByTestId('table')
expect(table.textContent?.includes('item_A')).toBeTruthy() // --> true
expect(table.textContent?.includes('item_Z')).toBeFalsy() // --> true
// getting the list which is a child component of table
const list = table.children[0]
fireEvent.scroll(list, {target: {scrollY: 100}})
expect(table.textContent?.includes('item_A')).toBeFalsy() // --> false
expect(table.textContent?.includes('item_Z')).toBeTruthy() // --> false
})
})
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import { render, screen, fireEvent } from '@testing-library/react';
import MyApp from './MyApp ';
const initialState = {};
const mockStore = configureStore(initialState);
describe('<MyApp />', () => {
it('click button and shows modal', () => {
render(
<Provider store={mockStore}>
<MyApp />
</Provider>
);
fireEvent.click(screen.getByText('ADD MIOU'));
expect(queryByText('Add MIOU Setting')).toBeInTheDocument();
});
});
Run Code Online (Sandbox Code Playgroud)
我正在使用 jest 和 redux 工具包reactjs,并尝试模拟商店来编写测试。但出现以下错误
类型错误:store.getState 不是函数
有没有什么办法解决这一问题?我错过了什么吗?
我已经使用 jest 版本、26.0.0react-testing-library 和 node 版本编写了单元测试14.2.0。下面是我的 React 功能组件,它有一个按钮,单击后会发出 ajax 调用来下载报告文件。
const ReportListTable = () => {
const { downloadReports } = useReports();
const onClickDownload = () => {
let fileName = `Report.zip`;
downloadReports()
.then((response) => response.arrayBuffer())
.then((data) => {
const blob = new Blob([data], { type: "octet/stream", endings: "native" });
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.setAttribute("href", url);
anchor.setAttribute("download", fileName);
anchor.click();
window.URL.revokeObjectURL(url);
})
.catch((error?: Error | Response) => {
if (error instanceof Error) { …Run Code Online (Sandbox Code Playgroud) 我正在使用 Jest 和 React 测试库来测试组件。
我正在尝试测试模式,但我遇到了一个奇怪的问题。当我尝试在触发事件之前通过文本获取“模态标题”时,我收到错误,因为渲染的文档中不存在“模态标题”。如果我在触发“打开模态”按钮后尝试查找“模态标题”,它就会起作用。但我还想测试模态在触发事件之前不存在。所以我决定期望“模态标题”为假,但这不起作用。到目前为止,我已经尝试过 toBe(false)、toBeFalsy()、toBeNull() ,甚至尝试查看长度是否为 0,但没有任何提到的工作。我该如何解决这个问题。
it('Test Modal', () => {
const { getByText } = render(<TestApp />);
expect(getByText('Modal Title')).toBe(false);
fireEvent.click(getByText('Open Modal'));
expect(getByText('Modal Title')).toBeTruthy();
})
Run Code Online (Sandbox Code Playgroud) 当使用 s 测试组件时<Link>,例如在我对React-router 路由中基于路由的测试的推荐方法的回答中,我经常使用以下模式来访问当前的location测试目的:
const renderInRouter = () => {\n const history = createMemoryHistory();\n const wrapper = render(\n <Router history={history}>\n <MyPage />\n </Router>\n );\n return { ...wrapper, history };\n}\nRun Code Online (Sandbox Code Playgroud)\n这在 v5.3 之前工作得很好,但升级到 v6 后我得到:
\n FAIL ./demo.test.js\n \xe2\x9c\x95 works (205 ms)\n\n \xe2\x97\x8f works\n\n TypeError: Cannot read properties of undefined (reading \'pathname\')\n\n at Router (../packages/react-router/index.tsx:281:5)\n\n ...\nRun Code Online (Sandbox Code Playgroud)\n迁移文档中未涵盖此用例,v6 到目前为止还没有测试指南,尽管API 参考确实表明history不再需要该 prop:
interface RouterProps {\n basename?: string;\n children?: …Run Code Online (Sandbox Code Playgroud) reactjs jestjs react-router react-router-dom react-testing-library
我正在建立一个 monorepo,在其中构建一个反应应用程序,我将在其中使用打字稿。我们想使用 jest 来测试后端功能,使用 React-Testing-Library 来测试前端功能。我应该安装 jest 并在根目录中添加配置文件还是直接在“后端”包中添加配置文件?
与另一种相比,这样做的优点/缺点是什么?
感谢您的帮助。
我有一个简单的 React 组件,最初有一个 Tailwind CSS 类,hidden该类应用 CSSdisplay: none并将该类更改为visible单击按钮。当我用expect().not.toBeVisible()它进行测试时,它告诉我该元素在具有类时已经可见hidden。
如果我不使用 Tailwind CSS 并使用法线,style={{display: 'none'}}它将正确识别该元素不可见。这显然意味着问题出在 Tailwind CSS 上。
这是我的测试:
test("Notification bar should be initially hidden but visible on click", async () => {
render(<Notifications />);
expect(await screen.findByTestId("list")).not.toBeVisible();
// this test fails while the element already has a Tailwind CSS class of "hidden"
});
Run Code Online (Sandbox Code Playgroud)
虽然这是我的组件:
<ul className="hidden" data-testid="list">
<li>item 1</li>
</ul>
Run Code Online (Sandbox Code Playgroud) reactjs ×9
jestjs ×7
redux ×2
unit-testing ×2
javascript ×1
monorepo ×1
react-router ×1
react-window ×1
tailwind-css ×1
typescript ×1