jeudi 12 décembre 2019

Mock response value in custom Ajax function using Jest

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 ) );?

Aucun commentaire:

Enregistrer un commentaire