1

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.

2
  • your jqXHR methods don't invoke the given callbacks (cb)
    – Teneff
    Sep 23, 2020 at 9:26
  • I already tried not working Sep 23, 2020 at 9:27

1 Answer 1

1

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

2
  • Thanks a lot for code snippet.I am getting this exception ` TypeError: $messageBar.html is not a function` Sep 23, 2020 at 12:16
  • @santoshsingh take a look at how have I mocked jquery at the top of the test file
    – Teneff
    Sep 23, 2020 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.