React unit test with Jest & TS (問題記錄)

為action,redux及saga創(chuàng)建測試文件

tsconfig中添加paths


在jest.config.js中添加moduleNameMapper




一:Actions

?e.g: 為LAYOUT_INIT_HEADER創(chuàng)建測試方法:(此處將所有的action放入對應(yīng)的actionFactory方法中,方便各方法調(diào)用)


在__test__文件夾下創(chuàng)建對應(yīng)的test文件,layout.test.ts (調(diào)用對應(yīng)的actionFactory方法后返回的action符合預(yù)期)


二:Reducers

layout reducer:.


創(chuàng)建對應(yīng)的測試文件 (傳遞action給reducer,應(yīng)返回符合預(yù)期的結(jié)果)


三:Saga

對應(yīng)的saga方法:

export function* fetchUser(action) {

? ? try {

? ? ? ? const response = yield call(axios.get, REST_MY_PROFILE);

? ? ? ? const serviceList = yield call(axios.get, REST_MY_SERVICE_LIST);

? ? ? ? let tempServiceList = [];

? ? ? ? serviceList.data.forEach((item) => {

? ? ? ? ? ? tempServiceList.push({

? ? ? ? ? ? ? ? name: item.name,

? ? ? ? ? ? ? ? url: item.location

? ? ? ? ? ? });

? ? ? ? });

? ? ? ? let signedInUser = {

? ? ? ? ? ? email: response.data.email,

? ? ? ? ? ? firstName: response.data.firstName,

? ? ? ? ? ? lastName: response.data.lastName,

? ? ? ? ? ? company: response.data.company,

? ? ? ? ? ? notifications: response.data.notifications,

? ? ? ? ? ? urls: {

? ? ? ? ? ? ? ? settings: '',

? ? ? ? ? ? ? ? notifications: '',

? ? ? ? ? ? ? ? logout: ''

? ? ? ? ? ? },

? ? ? ? ? ? services: tempServiceList

? ? ? ? };

? ? ? ? response.payload = signedInUser;

? ? ? ? let returnAction = null;

? ? ? ? if (response.status === 200) {

? ? ? ? ? ? returnAction = LayoutActionFactory.userFetchSucceed({ ...response.payload, ...{ isBusy: false } });

? ? ? ? }

? ? ? ? yield put(returnAction);

? ? } catch (e) {

? ? ? ? if (e.response.status === 401) {

? ? ? ? ? ? window.location.href = `/auth?redirect=${window.location}`;

? ? ? ? ? ? return;

? ? ? ? } else {

? ? ? ? ? ? notification.notify("Profile Settings error happends:" + e.response.status + "--" + e.response.statusText, ToastType.error);

? ? ? ? }

? ? ? ? notification.notify("Header init failed now using testing data:", ToastType.error);

? ? ? ? let returnAction = LayoutActionFactory.error({ ...e.response.payload, ...{ isBusy: false } }) as any;

? ? ? ? yield put(returnAction);

? ? }

}

對應(yīng)的測試文件

*將對應(yīng)的mock data傳遞給generator

在package.json中添加對應(yīng)命令并執(zhí)行


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容