React unit test with Jest & TS (问题记录)

为action,redux及saga创建测试文件

tsconfig中添加paths


在jest.config.js中添加moduleNameMapper




一:Actions

 e.g: 为LAYOUT_INIT_HEADER创建测试方法:(此处将所有的action放入对应的actionFactory方法中,方便各方法调用)


在__test__文件夹下创建对应的test文件,layout.test.ts (调用对应的actionFactory方法后返回的action符合预期)


二:Reducers

layout reducer:.


创建对应的测试文件 (传递action给reducer,应返回符合预期的结果)


三:Saga

对应的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);

    }

}

对应的测试文件

*将对应的mock data传递给generator

在package.json中添加对应命令并执行


你可能感兴趣的:(React unit test with Jest & TS (问题记录))