问题 在Jest中进行XHR测试


我想测试AJAX方法(vanilla XHR),我找不到这样做的方法 笑话 框架。我发现 mock-ajax.js 对于Jasmine,问题是我找不到安装它的方法。

是否有更好的单元测试Ajax函数的方法 笑话


10107
2018-02-18 13:27


起源



答案:


您可以在Jest中测试XHR而无需额外的包。这是辅助函数,它为XMLHttpRequest创建模拟对象:

let open, send, onload, onerror;

function createXHRmock() {
    open = jest.genMockFn();

    // be aware we use *function* because we need to get *this* 
    // from *new XmlHttpRequest()* call
    send = jest.genMockFn().mockImpl(function(){   
        onload = this.onload.bind(this);
        onerror = this.onerror.bind(this);
    });

    const xhrMockClass = function () {
        return {
            open,
            send
        };
    };

    window.XMLHttpRequest = jest.genMockFn().mockImpl(xhrMockClass);
}

你可以在测试中使用它如下:

it('XHR success', () => {
    createXHRmock();

    // here you should call GET request

    expect(open).toBeCalledWith('GET', 'http://example.com', true);
    expect(send).toBeCalled();

    // call onload or onerror
    onload();

    // here you can make your assertions after onload
});

9
2017-11-04 17:02



我想这就是现在 jest.fn().mockImplementation 来自 文档 - Peter


答案:


您可以在Jest中测试XHR而无需额外的包。这是辅助函数,它为XMLHttpRequest创建模拟对象:

let open, send, onload, onerror;

function createXHRmock() {
    open = jest.genMockFn();

    // be aware we use *function* because we need to get *this* 
    // from *new XmlHttpRequest()* call
    send = jest.genMockFn().mockImpl(function(){   
        onload = this.onload.bind(this);
        onerror = this.onerror.bind(this);
    });

    const xhrMockClass = function () {
        return {
            open,
            send
        };
    };

    window.XMLHttpRequest = jest.genMockFn().mockImpl(xhrMockClass);
}

你可以在测试中使用它如下:

it('XHR success', () => {
    createXHRmock();

    // here you should call GET request

    expect(open).toBeCalledWith('GET', 'http://example.com', true);
    expect(send).toBeCalled();

    // call onload or onerror
    onload();

    // here you can make your assertions after onload
});

9
2017-11-04 17:02



我想这就是现在 jest.fn().mockImplementation 来自 文档 - Peter


开玩笑api已经改变了一点。这就是我使用的。它没有做任何事情,但它足以渲染我的组件。

const xhrMockClass = () => ({
  open            : jest.fn(),
  send            : jest.fn(),
  setRequestHeader: jest.fn()
})

window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass)

并在测试文件中:

import '../../__mock__/xhr-mock.js'


7
2018-05-10 13:01



您的代码格式化有什么问题? - Michal
哈哈,首先是逗号没有“错误”(很多节点开发者都这么做),但在此期间我确实切换回逗号。将编辑。但是你没有理由进行投票,而你可能遇到的任何其他问题都无法解决。 - ThaJay