我已经使用Hooks和Context构建了多个React功能组件。一切正常。现在,我需要为所有内容编写测试。我对如何与其中的一些人混为一谈感到困惑,因此想与社区接触。
操作 这是我其中一个动作文件的示例:
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文件?我不是说要与其他任何东西一起使用,而是指它吗? 从评论看来,我同意在此文件中没有可以直接测试的东西。
减速器 我的每个Reducers文件都直接连接到并支持特定的上下文。这是我的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是分开的,并且有默认状态。鉴于此代码模式,并且我已经为Context的Reducers提供了一个单独的测试文件,那么对于Context而言,一个测试只能用于什么?
答案 0 :(得分:2)
与我的评论相同,我真的认为您应该阅读redux docs for writing tests,以便大致了解该怎么做。
但是由于您已经有一个reducer,所以您希望编写测试用例以遵循这种模式
这是一个代码示例:
it('adds a new car when there are no cars yet', () => {
// you want to put here values that WILL change, so that you don't risk
// a false positive in your unit test
const previousState = {
vehicles: [],
isDirty: false,
};
const state = reducer(previousState, { type: ADD_VEHICLE });
expect(state).toEqual({
vehicles: [{
id: 1,
vin: '',
license: '',
}],
isDirty: true,
});
});
it('adds a new car when there are existing cars already, () => {
// ...
});
我还建议使用动作创建者,而不是直接创建动作对象,因为它更具可读性:
// actions.js
export const addVehicle = () => ({
type: ADD_VEHICLE
})
// reducer.test.js
it('adds a new car when there are no cars yet', () => {
//...
const state = reducer(previousState, actions.addVehicle());