【发布时间】:2020-03-21 02:51:45
【问题描述】:
我已经使用 Hooks 和 Context 构建了多个 React 功能组件。一切正常。现在我需要为所有内容编写测试。我对如何与其中一些人一起前进感到困惑,因此想与社区联系。
操作 以下是我的一个 Actions 文件的示例:
export const ADD_VEHICLE: 'ADD_VEHICLE' = 'ADD_VEHICLE';
export const UPDATE_VEHICLE: 'UPDATE_VEHICLE' = 'UPDATE_VEHICLE';
type AddVehicleAction = {type: typeof ADD_VEHICLE, isDirty: boolean};
type UpdateVehicleAction = {type: typeof UPDATE_VEHICLE, id: number, propName: string, payload: string | number};
export type VehiclesActions =
| AddVehicleAction
| UpdateVehicleAction;
我应该如何测试这个 Actions 文件?我的意思不是与其他任何东西结合,我的意思是它,而且只有它? 从 cmets 看来,我同意此文件中没有可直接测试的内容。
减速器 我的每个 Reducers 文件都直接连接到并支持特定的 Context。这是我的一个 Reducers 文件的示例:
import type { VehiclesState } from '../VehiclesContext';
import type { VehiclesActions } from '../actions/Vehicles';
import type { Vehicle } from '../SharedTypes';
import { ADD_VEHICLE,
UPDATE_VEHICLE
} from '../actions/Vehicles';
export const vehiclesReducer = (state: VehiclesState, action: VehiclesActions) => {
switch (action.type) {
case ADD_VEHICLE: {
const length = state.vehicles.length;
const newId = (length === 0) ? 0 : state.vehicles[length - 1].id + 1;
const newVehicle = {
id: newId,
vin: '',
license: ''
};
return {
...state,
vehicles: [...state.vehicles, newVehicle],
isDirty: action.isDirty
};
}
case UPDATE_VEHICLE: {
return {
...state,
vehicles: state.vehicles.map((vehicle: Vehicle) => {
if (vehicle.id === action.id) {
return {
...vehicle,
[action.propName]: action.payload
};
} else {
return vehicle;
}
}),
isDirty: true
};
}
如果您想为这个 Reducers 文件构建测试,您会使用什么方法?我的想法是像这样渲染 DOM:
function CustomComponent() {
const vehiclesState = useVehiclesState();
const { isDirty,
companyId,
vehicles
} = vehiclesState;
const dispatch = useVehiclesDispatch();
return null;
}
function renderDom() {
return {
...render(
<VehiclesProvider>
<CustomComponent />
</VehiclesProvider>
)
};
}
虽然上面的代码确实运行了,但我现在遇到的问题是 vehiclesState 和 dispatch 在我的测试代码中都无法访问,所以我试图弄清楚如何在每个 describe / it 中“显示”它们构造。任何建议将不胜感激。
上下文 我的上下文遵循 Kent C. Dodds 概述的相同模式:https://kentcdodds.com/blog/how-to-use-react-context-effectively - StateContext 和 DispatchContext 是分开的,并且有一个默认状态。鉴于此 Code Pattern,并且我已经为 Context 的 Reducers 准备了一个单独的测试文件,那么具体可以针对 Context 测试什么?
【问题讨论】:
-
感觉太宽泛了!此外,这取决于您要测试的内容,然后实施主要基于意见。
-
真的不清楚你在问什么。您在上面发布的代码只是类型声明,没有什么要测试的。您可能想用更明确的问题更新您的帖子
-
@EmileBergeron 你能详细说明一下吗?
-
@ChristopherFrancisco 我已根据您的反馈更新了问题。对于初学者,我相信我已经同意测试 Actions 文件是不可能/不必要的。您将如何测试一个 Reducers 文件,例如我所概述的文件。并且测试 Context(使用类似于 Kent C. Dodds 的代码)是否是不必要的,因为在测试 Reducer 时会执行所有基本操作?
-
你读过关于编写测试的 redux 文档吗? redux.js.org/recipes/writing-tests这对你来说可能是一个好的开始
标签: javascript reactjs jestjs react-context react-testing-library