XHR testing in Jest

前端 未结 6 2059
暖寄归人
暖寄归人 2020-12-05 18:41

I want to test AJAX methods (vanilla XHR) and I can\'t find the way to do it with Jest framework. I found mock-ajax.js for Jasmine, the problem

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 18:56

    This is how I did it.

    test.js

    const open = jest.fn();
    const onload = jest.fn((x) => {/*  */});
    const onerror = jest.fn();
    const send = jest.fn(function(){
        this.onload()
    })
    
    const xhrMockClass = function () {
        return {
            open,
            send,
            onerror,
            onload
        };
    };
    
    global.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);
    
    // ...
    
    test('Should make a request', () => {
     // do stuff to make request
    
     expect(send).toHaveBeenCalled()
     expect(onload).toHaveBeenCalledWith(/*  */)
     expect(open).toHaveBeenCalledWith('GET', 'some/url', true)
    })
    

提交回复
热议问题