代码之家  ›  专栏  ›  技术社区  ›  ketan

Jest XMLHttpRequest模拟请求显示错误

  •  1
  • ketan  · 技术社区  · 6 年前

    我有以下功能。

    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); 
    }
    

    我在用 开玩笑 用于单元测试。

    我在某个地方读到,测试原始XMLHttpRequest是个坏主意。是真的吗?

    所以,创建于 XHR testing in Jest 回答

    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();
    });
    

    但是,我有以下错误。

    XHR成功

    期望(jest.fn()).toBeCalledWith(期望)

    应使用以下函数调用模拟函数: [“获取”,“ http://example.com “,对] 但没人叫它。

    我犯了一个愚蠢的错误,但是,我不知道。我在单元测试方面很差。

    任何帮助都将不胜感激。

    0 回复  |  直到 6 年前
        1
  •  0
  •   Dan Caseley    5 年前

    看着 answer you linked ,示例答案中有一点:

    createXHRmock();
    
    // here you should call GET request
    
    expect(open).toBeCalledWith('GET', 'http://example.com', true);
    

    在这两个语句之间,需要调用sendWeatherrequest,并修改expect(open)expect从 generateUrl 功能。

    例如

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