javascript - 使用 Jest 在自定义 Ajax 函数中模拟响应值
问题描述
我们将 axios 替换为自定义 ajax 函数以避免 Promise 和任何 IE11 不支持的功能。
/* _utility.js */
export const ajaxGet = ( config ) => {
const httpRequest = new XMLHttpRequest();
const defaultConfig = Object.assign( {
url: '',
contentType: 'application/json',
success: ( response ) => {},
}, config );
httpRequest.onreadystatechange = function() {
if ( httpRequest.readyState === XMLHttpRequest.DONE ) {
if ( httpRequest.status >= 200 && httpRequest.status < 300 ) {
defaultConfig.success( JSON.parse( httpRequest.responseText ) );
}
}
};
httpRequest.open( 'GET', defaultConfig.url, true );
httpRequest.send();
};
这在 React JS 中以下列方式使用:
/* AggregationPageContent */
export class AggregationPageContent extends React.Component {
constructor() {
super();
this.state = {
data: false,
};
}
componentDidMount() {
const { restUrl, termId } = tlsAggregationPage;
ajaxGet( {
url: `${ restUrl }/category/${ termId }?page=${ this.state.page }`,
success: ( response ) => {
this.setState( {
data: response,
page: 1,
}
},
} );
}
}
在使用 axios 时,响应是这样模拟的:
/* AggregationPage.test.js */
import { aggregationData } from '../../../stories/aggregation-page-data-source';
jest.mock( 'axios' );
test( 'Aggregation page loads all components.', async () => {
global.tlsAggregationPage = {
id: 123,
resultUrl: 'test',
};
axios.get.mockResolvedValue( { data: aggregationData } );
我试图嘲笑响应,ajaxGet
但我处于死胡同。如何模拟传递给的值defaultConfig.success( JSON.parse( httpRequest.responseText ) );
?
解决方案
这是单元测试解决方案:
_utility.js
:
export const ajaxGet = (config) => {
const httpRequest = new XMLHttpRequest();
const defaultConfig = Object.assign(
{
url: '',
contentType: 'application/json',
success: (response) => {},
},
config,
);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
defaultConfig.success(JSON.parse(httpRequest.responseText));
}
}
};
httpRequest.open('GET', defaultConfig.url, true);
httpRequest.send();
};
AggregationPageContent.jsx
:
import React from 'react';
import { ajaxGet } from './_utility';
const tlsAggregationPage = { restUrl: 'https://example.com', termId: '1' };
export class AggregationPageContent extends React.Component {
constructor() {
super();
this.state = {
data: false,
page: 0,
};
}
componentDidMount() {
const { restUrl, termId } = tlsAggregationPage;
ajaxGet({
url: `${restUrl}/category/${termId}?page=${this.state.page}`,
success: (response) => {
this.setState({
data: response,
page: 1,
});
},
});
}
render() {
return null;
}
}
AggregationPage.test.jsx
:
import { AggregationPageContent } from './AggregationPageContent';
import { ajaxGet } from './_utility';
import { shallow } from 'enzyme';
jest.mock('./_utility.js', () => {
return {
ajaxGet: jest.fn(),
};
});
describe('AggregationPageContent', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should pass', () => {
let successCallback;
ajaxGet.mockImplementationOnce(({ url, success }) => {
successCallback = success;
});
const wrapper = shallow(<AggregationPageContent></AggregationPageContent>);
expect(wrapper.exists()).toBeTruthy();
const mResponse = [];
successCallback(mResponse);
expect(wrapper.state()).toEqual({ data: [], page: 1 });
expect(ajaxGet).toBeCalledWith({ url: 'https://example.com/category/1?page=0', success: successCallback });
});
});
覆盖率 100% 的单元测试结果:
PASS src/stackoverflow/59299691/AggregationPage.test.jsx (13.603s)
AggregationPageContent
✓ should pass (13ms)
----------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
AggregationPageContent.jsx | 100 | 100 | 100 | 100 | |
----------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.403s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59299691
推荐阅读
- scala - 摆脱 Scala 列表中的迭代器
- kubernetes - 使用 minikube 时出现 Grafana volumeMount 错误
- c - setuid-root 程序中的权限问题
- python - 在某些条件下从 numpy 数组中删除特定值
- .net - ASP.NET MVC 在发布到服务器时自动更改连接字符串
- javascript - 使用所有函数参数而不必枚举它们
- php - 组合来自不同 MySQL 条目的数组并删除重复项
- tomcat - 如何在 Tomcat 9 中创建自定义类路径?
- c - 我可以在 C 程序中同时打开多少个临时文件?
- amazon-redshift - Redshift Dist 键、IDentity 列或连接列?列的基数,用于排序键的联接考虑