您好,登錄后才能下訂單哦!
要使用Jest測(cè)試Redux狀態(tài)管理,首先需要安裝Jest和相關(guān)依賴。然后,可以編寫針對(duì)reducer、action creators和selectors的單元測(cè)試。
npm install --save-dev jest redux-mock-store redux-actions
在項(xiàng)目根目錄下創(chuàng)建一個(gè)名為jest.config.js
的文件,并添加以下內(nèi)容:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
假設(shè)你有一個(gè)簡(jiǎn)單的Redux模塊,包括一個(gè)counterReducer
、兩個(gè)action creators(increment
和decrement
)以及一個(gè)selector(getCount
)。
counter.ts
:
// Actions
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
// Action Creators
export function increment() {
return { type: INCREMENT };
}
export function decrement() {
return { type: DECREMENT };
}
// Initial State
const initialState = {
count: 0,
};
// Reducer
export default function counterReducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
case DECREMENT:
return { ...state, count: state.count - 1 };
default:
return state;
}
}
// Selector
export function getCount(state) {
return state.count;
}
接下來,為這些函數(shù)編寫單元測(cè)試:
counter.test.ts
:
import { increment, decrement } from './counter';
import counterReducer, { getCount } from './counter';
describe('counter actions', () => {
it('should create an increment action', () => {
expect(increment()).toEqual({ type: 'INCREMENT' });
});
it('should create a decrement action', () => {
expect(decrement()).toEqual({ type: 'DECREMENT' });
});
});
describe('counter reducer', () => {
it('should handle initial state', () => {
expect(counterReducer(undefined, {})).toEqual({ count: 0 });
});
it('should handle INCREMENT action', () => {
expect(counterReducer({ count: 0 }, { type: 'INCREMENT' })).toEqual({ count: 1 });
});
it('should handle DECREMENT action', () => {
expect(counterReducer({ count: 1 }, { type: 'DECREMENT' })).toEqual({ count: 0 });
});
});
describe('getCount selector', () => {
it('should return the count', () => {
expect(getCount({ count: 42 })).toBe(42);
});
});
在package.json
中添加一個(gè)test
腳本:
{
"scripts": {
"test": "jest"
}
}
然后運(yùn)行npm test
以執(zhí)行所有測(cè)試。
這只是一個(gè)簡(jiǎn)單的示例,實(shí)際項(xiàng)目中可能會(huì)更復(fù)雜。但是,基本原則是相同的:為每個(gè)Redux模塊編寫單元測(cè)試,確保它們的功能正常。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。