Reputation: 3788
We replaced axios with a custom ajax function to avoid Promises and any features that aren't supported by 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();
};
This is used in React JS the following way:
/* 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,
}
},
} );
}
}
While working with axios, the response was mocked this way:
/* 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 } );
I've tried to mock the response for ajaxGet
but I'm at a dead end. How can I mock the value which is passed to defaultConfig.success( JSON.parse( httpRequest.responseText ) );
?
Upvotes: 0
Views: 657
Reputation: 102237
Here is the unit test solution:
_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 });
});
});
Unit test result with 100% coverage:
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
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59299691
Upvotes: 1