2
votes

I have following function.

export function sendWeatherrequest(countryName) {
    let xmrRequest = new XMLHttpRequest();
    xmrRequest.onload = requestListener;
    xmrRequest.onerror = requestError;

    xmrRequest.open('get', generateUrl(name), true);
    xmrRequest.send(); 
}

function requestListener() {
    let data = JSON.parse(this.responseText);
    displayPage(data); 
}

I am using jest for unit test.

As, i read somewhere that it is bad idea to test original XMLHttpRequest. Is it true?

So, created following from XHR testing in Jest answer

let open, send, status, onload, setRequestHeader, response;
function createXHRmock() {
    open = jest.fn();
    status = 200;
    response = JSON.stringify([{
        title: 'some data.',
        weather: 'wind'
    }]);

    send = jest.fn().mockImplementation(function(){   
        onload = this.onload.bind(this);
        onerror = this.onerror.bind(this);
    });

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

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

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

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

    onload();
});

But, i am getting following error.

XHR success

expect(jest.fn()).toBeCalledWith(expected)

Expected mock function to have been called with: ["GET", "http://example.com", true] But it was not called.

My be i done some stupid mistake but, can't figureout. I am very poor in unit testing.

Any help would be greatly appreciated.

1
looks like your mock has not actually mocked XHR. maybe the fastest solution is to use any of existing mock xhr package like xhr-mock? - skyboyer
@skyboyer It test original API url? I mean i need to pass original API URL? - ketan
open only gets called in sendWeatherrequest but sendWeatherrequest is never called in your test - Brian Adams

1 Answers

0
votes

Looking at the answer you linked, there's a bit in the example answer:

createXHRmock();

// here you should call GET request

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

In between the two statements, you need to invoke your sendWeatherrequest, and modify your expect(open) expect the URL that comes back from your generateUrl function.

e.g.

createXHRmock();

sendWeatherrequest('FR')

expect(open).toBeCalledWith('GET', 'http://theweather.net/france', true);