santosh singh
santosh singh

Reputation: 28642

Test jquery ajax call using Jest

I have following javascript code in my script file and I am writing test for the following function using JEST

function getData() {
    var $messageBar = $("#message-bar");
    var messageBarLength = $messageBar.length;
    if (messageBarLength == 0) return;
    var apiUrl = $messageBar.attr("data-url");
    if (messageBarLength && apiUrl) {
        apiUrl = apiUrl.replace("{c}/{l}/{s}/{cs}"
        
        $.get(apiUrl)
            .done(function (html) {
                if (html) {
                    $messageBar.html(html);
                } else {
                    $messageBar.hide();
                }
            })
            .fail(function (error) {
                $messageBar.hide();
            });
    }
}

And my jest test is as below

test("test",
    () => {

        const jqXHR = {
            done: jest.fn().mockImplementation(cb => {
                
                return this;
            }),
            fail: jest.fn().mockImplementation(cb => {
               
                return this;
            })
        };
        
        $.get = jest.fn().mockImplementation(() => jqXHR);
        $.get();
        getData();
        expect($.get).toHaveBeenCalled();
    });

Test is running fine but in code coverage, its showing done and 'fail` is not covered. I already spent one day but did not find any solution Any help on this will be highly appreciated.

Upvotes: 1

Views: 1137

Answers (1)

Teneff
Teneff

Reputation: 32148

Since your XHR.done callback has branches (when it's called with html and without html) you will have to mock it as a function that calls the callback

  • once with a value

          const xhr = {
            done: jest.fn((cb) => {
              cb();
              return xhr;
            }),
            fail: jest.fn((cb) => {
              cb();
              return xhr;
            }),
          };
    
  • once without a value

          const xhr = {
            done: jest.fn((cb) => {
              cb('<span>some HTML</span>');
              return xhr;
            }),
            fail: jest.fn((cb) => {
              cb();
              return xhr;
            }),
          };
    

here is a working example with 100% coverage

Upvotes: 1

Related Questions