我有一个简单的仪表板组件,它依赖于 React 上下文来管理身份验证。它包含一个自定义挂钩useAuth来提取当前用户以及与身份验证相关的功能:登录、注销等。
这是上下文文件AuthContext.js::
import React, { createContext, useContext, useState, useEffect } from "react";
import { auth } from "../config/firebase";
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true);
function signup(email, password) {
return auth.createUserWithEmailAndPassword(email, password);
}
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password);
}
function logout() {
return auth.signOut();
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) …Run Code Online (Sandbox Code Playgroud)有没有办法用react-testing-library触发自定义事件?我在他们的文档中找不到这样的例子。
useEffect(() => {
document.body.addEventListener('customEvent', onEvent);
}, []);
Run Code Online (Sandbox Code Playgroud)
我想触发自定义事件(例如fireEvent('customEvent')并测试是否onEvent被调用。
reactjs jestjs react-testing-library react-hooks testing-library
我创建了一个沙箱来概述主要兴趣点: https://codesandbox.io/s/restless-dawn-nwy0l
请忽略格式,因为这只是我整理的 MWE。
当我在上面的沙箱中运行以下测试时
import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import Statistics from "../src/components/Block/Statistics";
import { IAction, IState } from "../src/typings/AppTypes";
import { AppReducer } from "../src/reducers/AppReducer";
import { AppContext } from "../src/context/AppContext";
import * as MineUtil from "../src/utils/mine";
import * as ConversionUtil from "../src/utils/conversion";
const state: IState = {
verifiedTrans: [
{
to: "A",
from: "B",
amount: 1.23,
message: "First Transaction",
signature: "AB1.23"
},
{
to: "A",
from: …Run Code Online (Sandbox Code Playgroud)reactjs jestjs react-testing-library use-reducer use-context
我花了一天的大部分时间试图解决这个极其烦人的错误。
我正在使用 redux-toolkit、MSW、RTK 查询和 React 测试库,目前正忙于编写一个测试简单登录流程的集成测试。
我遇到的问题是我正在一个测试套件中测试两种不同的场景,一种是成功登录,一种是失败登录。
当我一次运行一个时,我没有遇到任何问题,但是当我同时运行两个时,我会收到以下失败场景的错误。
TypeError: Cannot convert undefined or null to object
at Function.values (<anonymous>)
59 | (state, action) => {
60 | const { payload } = action;
> 61 | adapter.upsertMany(state, payload);
| ^
62 | }
63 | );
64 | },
at ensureEntitiesArray (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:794:27)
at splitAddedUpdatedEntities (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:799:19)
at upsertManyMutably (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:911:18)
at runMutator (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:772:17)
at Object.upsertMany (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:776:13)
at src/features/customers/store/customersSlice.ts:61:17
at recipe (node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:663:32)
at Immer.produce (node_modules/immer/src/core/immerClass.ts:94:14)
at node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:662:54
at Array.reduce (<anonymous>)
at node_modules/@reduxjs/toolkit/dist/redux-toolkit.cjs.development.js:641:29
at …Run Code Online (Sandbox Code Playgroud) 新的 Material UI DatePicker有一个 renderInput 属性,它获取渲染文本字段的函数。工作得很好,除了这个函数被渲染两次,并且在第一次渲染时它只接收它需要的一些道具。
当使用 React 测试库渲染时,仅发生第一次渲染。值得注意的是,endAdornment 不存在。因此不可能getByRole('button')单击按钮来打开选择器模式。
我尝试了waitFor()和的各种排列rerender(),但似乎无法显示按钮。
这是一个代码沙箱,显示了被注销的 renderInput 参数的两个版本。(我还在那里进行了一个测试来寻找按钮,但不幸的是我也对测试做了一些错误的事情并且它没有运行。)
有什么建议么?
我正在尝试为表单上的验证编写 RTL 测试。我正在使用useFormhook 来Yup进行验证。
我想测试的场景是当用户单击Add提交的按钮而不填写所有必填字段(标题和描述)时。在这种情况下,一些错误消息将在 from 的空输入下弹出。我想测试的正是这些消息。
我已经编写了测试,在其中找到标题、描述和“添加”按钮,但是当我单击“添加”按钮并执行操作时,screen.debug()错误消息不存在。
表单输入被截断:
<div className="Form__title">
<label className="Form__title--label" htmlFor="title">
Title
</label>
<input
{...register("title")}
type="text"
placeholder="Title..."
data-testid="titleInput"
/>
{errors?.title && (
<p data-testid="titleError">{errors.title.message}</p>
)}
</div>
Run Code Online (Sandbox Code Playgroud)
我的测试:
test("throws title must be at least 1 characters", async () => {
renderWithProviders(<TileForm />);
const error = "title must be at least 1 characters";
const addNewIdeaButton = screen.getByText("Add New Idea");
await userEvent.click(addNewIdeaButton);
const descriptionInput = screen.getByTestId("descriptionInput");
await userEvent.type(descriptionInput, "foo");
const addButton = …Run Code Online (Sandbox Code Playgroud) 我使用 react 测试库触发了组件的更改,我想检查组件状态的相应更改。是否可以检查组件的状态
我正在尝试将 Jest 用于新的 CRA 项目,但在尝试使用该findByText功能时遇到了问题。我安装了:
yarn add -D jest-environment-jsdom-sixteen
Run Code Online (Sandbox Code Playgroud)
并使用react-scripts test --env=jest-environment-jsdom-sixteen. 如果我在这里阅读这些问题时遇到了这个解决方案,它会很好地工作:
但是,我也在使用来自 VS 代码的 Jest 插件并且测试没有通过它。我尝试按照文档中的jest.config.js建议执行此操作:
module.exports = {
testEnvironment: 'jest-environment-jsdom-sixteen',
};
Run Code Online (Sandbox Code Playgroud)
但它仍然不起作用。
提前致谢。
我创建了一个反应打字稿应用程序npx create-react-app . --template typescript
我添加了一个基本测试文件
import '@testing-library/jest-dom/extend-expect'
const sumPositiveNumbers = (num1:number, num2: number) => {
return num1 + num2
}
describe('when test pass', () => {
test('should return an answer', () => {
expect(sumPositiveNumbers(4,5).toBe(9))
})
})
Run Code Online (Sandbox Code Playgroud)
我收到错误
TypeError: sumPositiveNumbers(...).toBe is not a function
Run Code Online (Sandbox Code Playgroud)
package.json 看起来像
{
"name": "test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^16.9.8",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"typescript": "^4.0.3",
"web-vitals": "^0.2.4" …Run Code Online (Sandbox Code Playgroud) 我正在关注 react-testing-library 的文档,以查找具有data-testid属性的元素是否已呈现。
react-testing-library 无法找到该元素,即使它存在。
测试
test('Renders step based on the active step', () => {
render(<RenderStep />, { initialState: { implOnboard: initialState } });
});
expect(screen.getByTestId('step-1')).toBeDefined(); // THROWS ERROR ?
}
Run Code Online (Sandbox Code Playgroud)
成分
// redux
const { activeStep } = useSelector((state) => state.implOnboard);
const renderStep = () => {
switch (activeStep) {
case 1:
console.log('Rendering this '); // THIS IS GETTING LOGGED TOO!
return (
<div data-testid="step-1">
<StepOne />
</div>
);
case 2:
return (
<div data-testid="step-2">
<StepTwo …Run Code Online (Sandbox Code Playgroud) reactjs ×9
jestjs ×4
material-ui ×1
msw ×1
react-hooks ×1
react-redux ×1
redux ×1
rtk-query ×1
use-context ×1
use-form ×1
use-reducer ×1