首页 > 解决方案 > 单元测试 Jest Node Fetch

问题描述

我正在尝试测试类方法的返回值。

此类方法从 API 中获取。

在测试时,我决定模拟 fetch 请求,这样我就不会访问网络。

我该怎么做?最好没有外部库。

A类

class ClassA {
    constructor() {
    }

    fetchSpotDate(pair) {
        const url = 'url';
        const query = 'query';
        fetch(url + query)
            .then(response => response.json())
            .then(json => new Date(json.settlement_date + "Z"))
            .catch(e => {
                log.error(e)
            });
    }
}

测试

it('should return correct date object format',  async () => {
        const mockSuccessResponse = {
          foo: 'bar', 
          settlement_date: '2020-06-29T00:00:00' 
        };
        const mockJsonPromise = Promise.resolve(mockSuccessResponse);
        const mockFetchPromise = Promise.resolve({json: () => mockJsonPromise})
        const expectedReturn = new Date("2020-06-29T00:00:00Z")
        global.fetch = jest.fn(() => mockFetchPromise);
        const classA = new ClassA();

        const result = await classA.fetchSpotDate('EURUSD')
        expect(???result Promise value???).toEqual(expectedReturn)
    });

标签: node.jsjestjsfetch

解决方案


推荐阅读