0

I want unit test this method (similar and inspired by How to use Jest to test file download?):

export const download = (file, filename) => {
  FileSaver.saveAs(file,filename);
};

And this is the test:

import { download } from "../../../utils/methods/utils";
import FileSaver from "file-saver";
import { item } from "../../__mocks__/responses/export"

describe("Test download", () => {
  it("Can handle download", () => {
    jest.mock("file-saver", () => ({
      saveAs: jest.fn()
    }));
    download(item.file, "test.xls");
    expect(FileSaver.saveAs).toHaveBeenCalledTimes(1);
  });
});

But I get

expect(received).toHaveBeenCalledTimes(expected)

Matcher error: received value must be a mock or spy function

Received has type:  function
Received has value: [Function anonymous]

   9 |     }));
  10 |     download(item.file, "test.xls");
> 11 |     expect(FileSaver.saveAs).toHaveBeenCalledTimes(1);
     |                              ^
  12 |   });
  13 | });
  14 |

  at Object.<anonymous> (src/__tests__/utils/methods/download.test.js:11:30)
sineverba
  • 5,059
  • 7
  • 39
  • 84

1 Answers1

0

I solved with SpyOn a mocked jest module not spying properly.

Issue was a small timeout.

it("Can handle download", () => {
    jest.mock("file-saver", () => ({
      saveAs: jest.fn()
    }));
    global.Blob = function (content, options) {
      return { content, options };
    };
    download(item.file, "test.xls");
    setTimeout(() => {
      expect(FileSaver.saveAs).toBeCalled();
      done();
    }, 10000);
  });
sineverba
  • 5,059
  • 7
  • 39
  • 84