javascript - 使用 Jest 在自定义 Ajax 函数中模拟响应值

标签 javascript reactjs testing mocking jestjs

我们用自定义 ajax 函数替换了 axios 以避免 IE11 不支持的 Promises 和任何功能。

/* _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

关于javascript - 使用 Jest 在自定义 Ajax 函数中模拟响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59299691/

相关文章:

javascript - SlickGrid:重新排序后排序不起作用

javascript - JS 中的行交换

javascript - 扩展运算符和 EsLint

javascript - 在 JSX : why does calling a function without the () work? 中调用 javascript 函数

testing - 如何设置 TestCafe 以在 CLI 中指定的环境中运行?

ruby - 读取urls.txt

javascript - Typescript通用返回值推断问题

javascript - jQuery:取消绑定(bind)所有事件然后执行处理程序

javascript - 放入时 undefined object throw new Error(error.response);

unit-testing - Angular2 whenStable() 不能与 observable 一起工作?