阅读本编文章请先看 jest+testing-library/react 单元测试 react+antd 的实践(一) 获取安装以及基本语法知识,下面讲从真实业务场景 antd+react 来写单元测试的例子
axios 测试
前端业务一般发请求用的是axios,会对axios进行包装,用请求拦截器 和 response拦截器 对请求和返回进行封装,场景是请求添加header: Authorization: Bearer token 返回根据返回结果进行判断采取不同的措施,例如登陆过期就跳登出,接口报错就弹窗错误消息,代码如下:
const createAxiosInstance = (): AxiosInstance => {
const instance = axios.create({
validateStatus: () => true,
});
instance.interceptors.request.use((config) => {
config.headers = {
...config.headers,
Authorization: `Bearer ${auth.getToken()}`,
};
return config;
});
instance.interceptors.response.use((res: AxiosResponse<Res>) => {
const data = res.data;
if (res.status === 401) {
message.error('登录状态已失效,请重新登录');
setTimeout(() => {
auth.logout();
}, 1000);
throw new Error('token invalid');
}
if (data.errorCode !== ErrCode.Success) {
message.error(data.errorInfo || '未知错误,请联系管理员');
throw data;
}
return { ...res, data };
});
return instance;
};
export class Api {
readonly axios = createAxiosInstance();
}
相对应的测试代码
jest.mock('../service/auth');
class MockApi extends Api {
client = this.axios;
}
let timerSpy: jest.SpyInstance;
const api = new MockApi();
beforeEach(() => {
jest.useFakeTimers();
timerSpy = jest.spyOn(global, 'setTimeout');
});
afterEach(() => {
timerSpy.mockRestore();
});
describe('test api/api.ts', () => {
it('接口请求拦截 headers:{Authorization: Bearer token}', () => {
const interceptorsRequest: any = api.client.interceptors.request;
expect(interceptorsRequest.handlers[0].fulfilled({})).toStrictEqual({
headers: { Authorization: 'Bearer token' },
});
});
it('当status=401时,弹出提示:登录状态已失效,请重新登录,1秒后登出', () => {
const interceptorsResponse: any = api.client.interceptors.response;
const data = { errorCode: 500 };
try {
interceptorsResponseResolved = interceptorsResponse.handlers[0].fulfilled({
data,
request: { responseURL: '' },
status: 401,
});
} catch (e) {
expect(e).toStrictEqual(new Error('token invalid'));
}
expect(message.error).toBeCalledWith('登录状态已失效,请重新登录');
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
expect(interceptorsResponseResolved).toBeUndefined();
jest.runAllTimers();
expect(auth.logout).toBeCalled();
});
it('当请求成功,返回结果当errorCode不为0时,弹出errorInfo的错误消息', () => {
let interceptorsResponseResolved: any;
const data = { errorCode: 500, errorInfo: 'errorInfo' };
try {
interceptorsResponseResolved = interceptorsResponse.handlers[0].fulfilled({
data,
request: { responseURL: '' },
status: 200,
});
} catch (e) {
expect(e).toStrictEqual(data);
}
expect(message.error).toBeCalledWith(data.errorInfo);
expect(interceptorsResponseResolved).toBeUndefined();
});
})
说明: jest.mock 模拟auth的方法 详见上一遍 antd 的 message 方法mock 见下面一章节
antd mock
antd message 方法模拟
对于没有dom的function单独测试时 不能直接判断有没有出现改message元素,可以判断message.error message.warn 方法有没有被调用 可以mock antd
export const messageErrorMock = jest.fn();
jest.mock('antd', () => {
const antd = jest.requireActual('antd');
return {
...antd,
message: {
...antd.message,
error: jest.fn,
},
};
});
这个代码可以放在测试文件开头 也可以放在根目录的setupTest.ts文件里 启动时会自动调用 在测试时 向上面的例子就可以直接判断 expect(messageErrorMock).toBeCalledWith(data.errorInfo); 是否调用了这个方法 以及传入的参数。
|