Return a double in Jest JS - javascript

I have a simple function like this that I want to test:
const saveAs = (fileName, content, contentType) => {
const a = createDownloadLink(fileName, content, contentType)
a.click()
}
export const createDownloadLink = (fileName, content, contentType) => {
...
const a = document.createElement('a')
...
return a
}
export default saveAs
I want to test that when I call saveAs, createDownloadLink is called, and click is called on the result.
I have tried mocking createDownloadLink and creating a spy on it. However, I can't find how to test click on the result:
Jest JS test:
const createDownloadLink = jest.fn()
saveAs('file.html', '<h1>hello</h1>', 'test/plain;UTF-8')
expect(createDownloadLink).toBeCalled() // And return a double
// expect(double.click).toBeCalled
})

I know you have already answered your own question, but since you've stated you didn't like seperating your functionality in two files I may have an alternative solution. Since you are exporting both functions anyways may I propose you actually make both part of the same object? This would allow you to mock or spy on the module function easily. For example lets assume you have saver.js:
class Saver {
saveAs(fileName, content, contentType) {
const a = this.createDownloadLink(fileName, content, contentType)
a.click()
}
createDownloadLink(fileName, content, contentType) {
const a = document.createElement('a')
return a
}
}
const saver = new Saver();
export default saver;
Then you your test would look like this:
import saver from './saver'
describe('saveAs', () => {
it("calls click on download link", () => {
const click = jest.fn()
saver.createDownloadLink = jest.fn(() => ({ click }));
saver.saveAs('file.html', '<h1>hello</h1>', 'test/plain;UTF-8')
expect(click).toHaveBeenCalled();
})
})

I finally solved this by creating an intermediate object that I use as a double.
Unfortunately, I had to separate my functionality into 2 files in order to use `jest.mock.
import saveAs from './index'
import createDownloadLink from './utils'
jest.mock("./utils");
describe('saveAs', () => {
it("calls click on download link", () => {
const downloadLinkDouble = {}
const clickMock = jest.fn()
downloadLinkDouble.click = clickMock
createDownloadLink.mockImplementation(() => downloadLinkDouble)
saveAs('file.html', '<h1>hello</h1>', 'test/plain;UTF-8')
expect(clickMock).toHaveBeenCalled()
})
})

Related

How to mock fs module together with unionfs?

I have written a test case that successfully load files into virtual FS, and at the same time mounted a virtual volume as below
describe("should work", () => {
const { vol } = require("memfs");
afterEach(() => vol.reset());
beforeEach(() => {
vol.mkdirSync(process.cwd(), { recursive: true });
jest.resetModules();
jest.resetAllMocks();
});
it("should be able to mock fs that being called in actual code", async () => {
jest.mock("fs", () => {
return ufs //
.use(jest.requireActual("fs"))
.use(createFsFromVolume(vol) as any);
});
jest.mock("fs/promises", () => {
return ufs //
.use(jest.requireActual("fs/promises"))
.use(createFsFromVolume(vol) as any);
});
const { createFsFromVolume } = require("memfs");
const { ufs } = require("unionfs");
const { countFile } = require("../src/ops/fs");
vol.fromJSON(
{
"./some/README.md": "1",
"./some/index.js": "2",
"./destination": null,
},
"/app"
);
const result = ufs.readdirSync(process.cwd());
const result2 = ufs.readdirSync("/app");
const result3 = await countFile("/app");
console.log({ result, result2, result3 });
});
});
By using ufs.readdirSync, I can access to virtual FS and indeed result giving me files that loaded from disc into virtual FS, result2 representing /app which is a new volume created from vol.fromJSON.
Now my problem is I am unable to get the result for result3, which is calling countFile method as below
import fsPromises from "fs/promises";
export const countFile = async (path: string) => {
const result = await fsPromises.readdir(path);
return result.length;
};
I'm getting error
Error: ENOENT: no such file or directory, scandir '/app'
which I think it's because countFile is accessing the actual FS instead of the virtual despite I've had jest.mock('fs/promises')?
Please if anyone can provide some lead?
This is the function you want to unit test.
//CommonJS version
const fsPromises = require('fs/promises');
const countFile = async (path) => {
const result = await fsPromises.readdir(path);
return result.length;
};
module.exports = {
countFile
}
Now, how you would normally go about this, is to mock fsPromises. In this example specifically readdir() since that is the function being used in countFile.
This is what we call: a stub.
A skeletal or special-purpose implementation of a software component, used to develop or test a component that calls or is otherwise dependent on it. It replaces a called component.
const {countFile} = require('./index');
const {readdir} = require("fs/promises");
jest.mock('fs/promises');
beforeEach(() => {
readdir.mockReset();
});
it("When testing countFile, given string, then return files", async () => {
const path = "/path/to/dir";
// vvvvvvv STUB HERE
readdir.mockResolvedValueOnce(["src", "node_modules", "package-lock.json" ,"package.json"]);
const res = await countFile(path);
expect(res).toBe(4);
})
You do this because you're unit testing. You don't want to be dependent on other functions because that fails to be a unit test and more integration test. Secondly, it's a third-party library, which is maintained/tested by someone else.
Here is where your scenario applies. From my perspective, your objective isn't to test countFile() rather, to test fsPromises and maybe test functionality to read virtual file-systems: unionfs. If so then, fsPromises doesn't need to really be mocked.

How to mock axios.create([config]) function to return its instance methods instead of overriding them with mock?

I'm trying to mock axios.create() because I'm using its instance across the app and obviously need all of its implementation which is destroyed by the mock, thus cannot get the result of the get, post method properly.
This is how the code looks like in the actual file:
export const axiosInstance = axios.create({
headers: {
...headers
},
transformRequest: [
function (data, headers) {
return data;
},
],
});
const response = await axiosInstance.get(endpoint);
And here is the mock setup for axios inside the test file
jest.mock('axios', () => {
return {
create: jest.fn(),
get: jest.fn(() => Promise.resolve()),
};
}
);
How could I get all of the instance methods in the axiosInstance variable instead of just having a mock function which does nothing?
Documentation for axios.create and instance methods: https://github.com/axios/axios#instance-methods
You can use jest's genMockFromModule. It will generate jest.fn() for each of the modules's methods and you'll be able to use .mockReturnThis() on create to return the same instance.
example:
./src/__mocks__/axios.js
const axios = jest.genMockFromModule('axios');
axios.create.mockReturnThis();
export default axios;
working example
Edit:
from Jest 26.0.0+ it's renamed to jest.createMockFromModule
Ended up sticking with the axios mock and just pointing to that mock by assigning the axiosInstance pointer to created axios mock.
Basically as #jonrsharpe suggested
Briefly:
import * as m from 'route';
jest.mock('axios', () => {
return {
create: jest.fn(),
get: jest.fn(() => Promise.resolve()),
};
}
);
m.axInstance = axios
Would be very nice though if I could have gone without it.
Since I need to manage Axios instances, I need a way of retrieving the mocks that are created so I can manipulate the responses. Here's how I did it.
import type { AxiosInstance, AxiosStatic } from 'axios';
const mockAxios = jest.createMockFromModule<AxiosStatic>('axios') as jest.Mocked<AxiosStatic>;
let mockAxiosInstances: jest.Mocked<AxiosInstance>[] = [];
mockAxios.create = jest.fn((defaults) => {
const mockAxiosInstance = jest.createMockFromModule<AxiosInstance>(
'axios'
) as jest.Mocked<AxiosInstance>;
mockAxiosInstance.defaults = { ...mockAxiosInstance.defaults, ...defaults };
mockAxiosInstances.push(mockAxiosInstance);
return mockAxiosInstance;
});
export function getMockAxiosInstances() {
return mockAxiosInstances;
}
export function mostRecentAxiosInstanceSatisfying(fn: (a: AxiosInstance) => boolean) {
return mockAxiosInstances.filter(fn).at(-1);
}
export function clearMockAxios() {
mockAxiosInstances = [];
}
export default mockAxios;
I added three additional methods:
clearMockAxios which clears the instance list
getMockAxiosInstances which gets the list of axios instances that are generated by axios.create
mostRecentAxiosInstanceSatisfying is a function that will do a filter to get the most recent axios instance that satisfies the predicate. This is what I generally use in the test case since React may render more than expected (or as expected) and I generally just need the last instance.
I use it as follows:
import { getMockAxiosInstances, mostRecentAxiosInstanceSatisfying, clearMockAxios } from '../../__mocks__/axios';
it("...", () => {
...
const mockAppClient = mostRecentAxiosInstanceSatisfying(
a => a.defaults.auth?.username === "myusername"
);
mockAppClient.post.mockImplementation(() => {
return Promise.resolve({ data: "AAA" })
})
... do something that calls the client ...
});
The following code works!
jest.mock("axios", () => {
return {
create: jest.fn(() => axios),
post: jest.fn(() => Promise.resolve()),
};
});

Jest with axios in window.api in Vue [duplicate]

I need to test a function which opens a new tab in the browser
openStatementsReport(contactIds) {
window.open(`a_url_${contactIds}`);
}
I would like to mock window's open function, so I can verify the correct URL is passed in to the open function.
Using Jest, I don't know how to mock window. I tried to set window.open with a mock function, but this way doesn't work. Below is the test case:
it('the correct URL is called', () => {
window.open = jest.fn();
statementService.openStatementsReport(111);
expect(window.open).toBeCalled();
});
But it gives me the error
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function anonymous]
What should I do to the test case?
The following method worked for me. This approach allowed me to test some code that should work both in the browser and in Node.js, as it allowed me to set window to undefined.
This was with Jest 24.8 (I believe):
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it('should return https://example.com', () => {
windowSpy.mockImplementation(() => ({
location: {
origin: "https://example.com"
}
}));
expect(window.location.origin).toEqual("https://example.com");
});
it('should be undefined.', () => {
windowSpy.mockImplementation(() => undefined);
expect(window).toBeUndefined();
});
Instead of window, use global:
it('the correct URL is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
You could also try:
const open = jest.fn()
Object.defineProperty(window, 'open', open);
There are a couple of ways to mock globals in Jest:
Use the mockImplementation approach (the most Jest-like way), but it will work only for those variables which has some default implementation provided by jsdom. window.open is one of them:
test('it works', () => {
// Setup
const mockedOpen = jest.fn();
// Without making a copy, you will have a circular dependency problem
const originalWindow = { ...window };
const windowSpy = jest.spyOn(global, "window", "get");
windowSpy.mockImplementation(() => ({
...originalWindow, // In case you need other window properties to be in place
open: mockedOpen
}));
// Tests
statementService.openStatementsReport(111)
expect(mockedOpen).toBeCalled();
// Cleanup
windowSpy.mockRestore();
});
Assign the value directly to the global property. It is the most straightforward, but it may trigger error messages for some window variables, e.g. window.href.
test('it works', () => {
// Setup
const mockedOpen = jest.fn();
const originalOpen = window.open;
window.open = mockedOpen;
// Tests
statementService.openStatementsReport(111)
expect(mockedOpen).toBeCalled();
// Cleanup
window.open = originalOpen;
});
Don't use globals directly (requires a bit of refactoring)
Instead of using the global value directly, it might be cleaner to import it from another file, so mocking will became trivial with Jest.
File ./test.js
jest.mock('./fileWithGlobalValueExported.js');
import { windowOpen } from './fileWithGlobalValueExported.js';
import { statementService } from './testedFile.js';
// Tests
test('it works', () => {
statementService.openStatementsReport(111)
expect(windowOpen).toBeCalled();
});
File ./fileWithGlobalValueExported.js
export const windowOpen = window.open;
File ./testedFile.js
import { windowOpen } from './fileWithGlobalValueExported.js';
export const statementService = {
openStatementsReport(contactIds) {
windowOpen(`a_url_${contactIds}`);
}
}
I'm directly assigning jest.fn() to window.open.
window.open = jest.fn()
// ...code
expect(window.open).toHaveBeenCalledTimes(1)
expect(window.open).toHaveBeenCalledWith('/new-tab','_blank')
In my component I need access to window.location.search. This is what I did in the Jest test:
Object.defineProperty(global, "window", {
value: {
location: {
search: "test"
}
}
});
In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:
function mockWindow(search, pathname) {
Object.defineProperty(global, "window", {
value: {
location: {
search,
pathname
}
},
writable: true
});
}
And reset after each test:
afterEach(() => {
delete global.window.location;
});
We can also define it using global in setupTests:
// File 'setupTests.js'
global.open = jest.fn()
And call it using global in the actual test:
// File 'yourtest.test.js'
it('the correct URL is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
I found an easy way to do it: delete and replace
describe('Test case', () => {
const { open } = window;
beforeAll(() => {
// Delete the existing
delete window.open;
// Replace with the custom value
window.open = jest.fn();
// Works for `location` too, eg:
// window.location = { origin: 'http://localhost:3100' };
});
afterAll(() => {
// Restore original
window.open = open;
});
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(window.open).toBeCalled(); // Happy happy, joy joy
});
});
The window object in Jest is self-mocking
One of the things unaddressed in other answers is a comment by the OP:
Using Jest, I don't know how to mock the window.
The window object is already mocked and can be referenced out of the box.
From the documentation:
Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser!
Example:
describe('i am a window', () => {
it('has a window object', () => {
expect(window).toBeTruthy(); // test will pass
});
});
You can try this:
import * as _Window from "jsdom/lib/jsdom/browser/Window";
window.open = jest.fn().mockImplementationOnce(() => {
return new _Window({ parsingMode: "html" });
});
it("correct url is called", () => {
statementService.openStatementsReport(111);
expect(window.open).toHaveBeenCalled();
});
If it's similar to the window location problem at window.location.href can't be changed in tests. #890, you could try (adjusted):
delete global.window.open;
global.window = Object.create(window);
global.window.open = jest.fn();
In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:
// setupTests.js
window.crypto = {
.....
};
Reference: setupFilesAfterEnv [array]
Try simply:
let windowOpenSpy: jest.SpyInstance;
beforeEach(() => {
windowOpenSpy = jest.spyOn(window, 'open');
});
it('should open window with dashboard url', () => {
expect(windowOpenSpy).toBeCalledWith('your URL', '_blank');
});
I have a utility function which allows me to mock any method on the window like so:
function givenMockWindowMethods(methods: Partial<{ [key in keyof Window]: jest.Mock<any, any> }>): () => void {
const mocks = Object.values(methods);
Object.entries(methods).forEach(([key, value]) => {
Object.defineProperty(window, key, { value });
});
return (): void => mocks.forEach((mock) => mock?.mockClear());
}
So if I need to mock the open method (or anything really) on the window, I can do:
const cleanupMocks = givenMockWindowMethods({ open: jest.fn() });
// expect(...).toBe(...)
//at the end of the test, clean it up
cleanupMocks()
You can test it:
describe('TableItem Components', () => {
let open_url = ""
const { open } = window;
beforeAll(() => {
delete window.open;
window.open = (url) => { open_url = url };
});
afterAll(() => {
window.open = open;
});
test('string type', async () => {
wrapper.vm.openNewTab('http://example.com')
expect(open_url).toBe('http://example.com')
})
})
const windowSpy = jest.spyOn(iFrame, "contentWindow", "get");
windowSpy.mockImplementation(() => ({
location: {
origin: "https://test.com",
href: "href",
hash: "hash"
}
}));
I tried a similar test, and it worked with me...
My code:
export const Blah = () => {
const BLAH = 'https://www.google.com/'
const handleBlah = () => {
window.open(BLAH, '_blank')
}
return (
<button onClick={handleBlah}> BLAHBLAH </button>
)
}
My test using Jest:
it('should be able to render "BLAHBLAH " button ', () => {
window.open = jest.fn();
const BLAH = 'https://www.google.com/'
const { getByText } = render(<Blah/>) // Get text by my page Blah
const buttonGoToBlah = getByText('BLAHBLAH') // Get button by text
fireEvent.click(buttonGoToBlah) // Simulate the click event
expect(window.open).toHaveBeenCalledTimes(1) // Expect the window.open have to been called at least once.
expect(window.open).toHaveBeenCalledWith(BLAH, '_blank'); // And the page should be the same called in my BLAH page
})

Jest URL.createObjectURL is not a function

I'm developping a reactJs application. I'm using jest to test my application.
I want to test a function that download a blob.
But unfortunately I receve this error:
URL.createObjectURL is not a function
my test function:
describe('download', () => {
const documentIntial = { content: 'aaa' };
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
window.navigator.msSaveOrOpenBlob = null;
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(0);
});
});
The function I want to test:
export const download = document => {
const blob = new Blob([base64ToArrayBuffer(document.content)], {
type: 'application/pdf',
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const fileURL = URL.createObjectURL(blob);
window.open(fileURL);
};
This would appear to be as simple as setting up URL on the Global in Jest. Something like
describe('download', () => {
const documentIntial = { content: 'aaa' };
global.URL.createObjectURL = jest.fn();
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
global.URL.createObjectURL = jest.fn(() => 'details');
window.navigator.msSaveOrOpenBlob = jest.fn(() => 'details');
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(1);
});
});
This should result in a test that you can also use for checking if global.URL.createObjectURL was called. As a side note: you may also run into a similar issue with window.open I would suggest mocking that as well if this becomes the case.
Since window.URL.createObjectURL is not (yet) available in jest-dom, you need to provide a mock implementation for it.
Don't forget to reset the mock implementation after each test.
describe("your test suite", () => {
window.URL.createObjectURL = jest.fn();
afterEach(() => {
window.URL.createObjectURL.mockReset();
});
it("your test case", () => {
expect(true).toBeTruthy();
});
});
jsdom, the JavaScript implementation of the WHATWG DOM used by jest doesn't implement this method yet.
You can find an open ticket about this exact issue on their github page where some workarounds are provided in comments. But if you need the blobURL to actually work you'll have to wait this FR is solved.
Workaround proposed in the comments of the issue for jest:
function noOp () { }
if (typeof window.URL.createObjectURL === 'undefined') {
Object.defineProperty(window.URL, 'createObjectURL', { value: noOp})
}
You just have to Write this in your setupTest.js
window.URL.createObjectURL = function() {};
The package jsdom-worker happens to provide this method, as well as adding support for web workers. The following worked for me:
npm install -D jsdom-worker
Then in package.json, edit or add a jest key:
{
...
"jest": {
"setupFiles": [
"jsdom-worker"
]
}
}
Just mocking the function global.URL.createObjectURL did not work for me, because the function was used by some modules during import and I got the error Jest URL.createObjectURL is not a function during import.
Instead it did help to create a file mockJsdom.js
Object.defineProperty(URL, 'createObjectURL', {
writable: true,
value: jest.fn()
})
Then import this file as the first import in your file containing the test
import './mockJsdom'
import { MyObjects} from '../../src/lib/mylib'
test('my test', () => {
// test code
}
Found here: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

How can I mock the JavaScript 'window' object using Jest?

I need to test a function which opens a new tab in the browser
openStatementsReport(contactIds) {
window.open(`a_url_${contactIds}`);
}
I would like to mock window's open function, so I can verify the correct URL is passed in to the open function.
Using Jest, I don't know how to mock window. I tried to set window.open with a mock function, but this way doesn't work. Below is the test case:
it('the correct URL is called', () => {
window.open = jest.fn();
statementService.openStatementsReport(111);
expect(window.open).toBeCalled();
});
But it gives me the error
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function anonymous]
What should I do to the test case?
The following method worked for me. This approach allowed me to test some code that should work both in the browser and in Node.js, as it allowed me to set window to undefined.
This was with Jest 24.8 (I believe):
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it('should return https://example.com', () => {
windowSpy.mockImplementation(() => ({
location: {
origin: "https://example.com"
}
}));
expect(window.location.origin).toEqual("https://example.com");
});
it('should be undefined.', () => {
windowSpy.mockImplementation(() => undefined);
expect(window).toBeUndefined();
});
Instead of window, use global:
it('the correct URL is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
You could also try:
const open = jest.fn()
Object.defineProperty(window, 'open', open);
There are a couple of ways to mock globals in Jest:
Use the mockImplementation approach (the most Jest-like way), but it will work only for those variables which has some default implementation provided by jsdom. window.open is one of them:
test('it works', () => {
// Setup
const mockedOpen = jest.fn();
// Without making a copy, you will have a circular dependency problem
const originalWindow = { ...window };
const windowSpy = jest.spyOn(global, "window", "get");
windowSpy.mockImplementation(() => ({
...originalWindow, // In case you need other window properties to be in place
open: mockedOpen
}));
// Tests
statementService.openStatementsReport(111)
expect(mockedOpen).toBeCalled();
// Cleanup
windowSpy.mockRestore();
});
Assign the value directly to the global property. It is the most straightforward, but it may trigger error messages for some window variables, e.g. window.href.
test('it works', () => {
// Setup
const mockedOpen = jest.fn();
const originalOpen = window.open;
window.open = mockedOpen;
// Tests
statementService.openStatementsReport(111)
expect(mockedOpen).toBeCalled();
// Cleanup
window.open = originalOpen;
});
Don't use globals directly (requires a bit of refactoring)
Instead of using the global value directly, it might be cleaner to import it from another file, so mocking will became trivial with Jest.
File ./test.js
jest.mock('./fileWithGlobalValueExported.js');
import { windowOpen } from './fileWithGlobalValueExported.js';
import { statementService } from './testedFile.js';
// Tests
test('it works', () => {
statementService.openStatementsReport(111)
expect(windowOpen).toBeCalled();
});
File ./fileWithGlobalValueExported.js
export const windowOpen = window.open;
File ./testedFile.js
import { windowOpen } from './fileWithGlobalValueExported.js';
export const statementService = {
openStatementsReport(contactIds) {
windowOpen(`a_url_${contactIds}`);
}
}
I'm directly assigning jest.fn() to window.open.
window.open = jest.fn()
// ...code
expect(window.open).toHaveBeenCalledTimes(1)
expect(window.open).toHaveBeenCalledWith('/new-tab','_blank')
In my component I need access to window.location.search. This is what I did in the Jest test:
Object.defineProperty(global, "window", {
value: {
location: {
search: "test"
}
}
});
In case window properties must be different in different tests, we can put window mocking into a function, and make it writable in order to override for different tests:
function mockWindow(search, pathname) {
Object.defineProperty(global, "window", {
value: {
location: {
search,
pathname
}
},
writable: true
});
}
And reset after each test:
afterEach(() => {
delete global.window.location;
});
We can also define it using global in setupTests:
// File 'setupTests.js'
global.open = jest.fn()
And call it using global in the actual test:
// File 'yourtest.test.js'
it('the correct URL is called', () => {
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
I found an easy way to do it: delete and replace
describe('Test case', () => {
const { open } = window;
beforeAll(() => {
// Delete the existing
delete window.open;
// Replace with the custom value
window.open = jest.fn();
// Works for `location` too, eg:
// window.location = { origin: 'http://localhost:3100' };
});
afterAll(() => {
// Restore original
window.open = open;
});
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(window.open).toBeCalled(); // Happy happy, joy joy
});
});
The window object in Jest is self-mocking
One of the things unaddressed in other answers is a comment by the OP:
Using Jest, I don't know how to mock the window.
The window object is already mocked and can be referenced out of the box.
From the documentation:
Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser!
Example:
describe('i am a window', () => {
it('has a window object', () => {
expect(window).toBeTruthy(); // test will pass
});
});
You can try this:
import * as _Window from "jsdom/lib/jsdom/browser/Window";
window.open = jest.fn().mockImplementationOnce(() => {
return new _Window({ parsingMode: "html" });
});
it("correct url is called", () => {
statementService.openStatementsReport(111);
expect(window.open).toHaveBeenCalled();
});
If it's similar to the window location problem at window.location.href can't be changed in tests. #890, you could try (adjusted):
delete global.window.open;
global.window = Object.create(window);
global.window.open = jest.fn();
In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:
// setupTests.js
window.crypto = {
.....
};
Reference: setupFilesAfterEnv [array]
Try simply:
let windowOpenSpy: jest.SpyInstance;
beforeEach(() => {
windowOpenSpy = jest.spyOn(window, 'open');
});
it('should open window with dashboard url', () => {
expect(windowOpenSpy).toBeCalledWith('your URL', '_blank');
});
I have a utility function which allows me to mock any method on the window like so:
function givenMockWindowMethods(methods: Partial<{ [key in keyof Window]: jest.Mock<any, any> }>): () => void {
const mocks = Object.values(methods);
Object.entries(methods).forEach(([key, value]) => {
Object.defineProperty(window, key, { value });
});
return (): void => mocks.forEach((mock) => mock?.mockClear());
}
So if I need to mock the open method (or anything really) on the window, I can do:
const cleanupMocks = givenMockWindowMethods({ open: jest.fn() });
// expect(...).toBe(...)
//at the end of the test, clean it up
cleanupMocks()
You can test it:
describe('TableItem Components', () => {
let open_url = ""
const { open } = window;
beforeAll(() => {
delete window.open;
window.open = (url) => { open_url = url };
});
afterAll(() => {
window.open = open;
});
test('string type', async () => {
wrapper.vm.openNewTab('http://example.com')
expect(open_url).toBe('http://example.com')
})
})
const windowSpy = jest.spyOn(iFrame, "contentWindow", "get");
windowSpy.mockImplementation(() => ({
location: {
origin: "https://test.com",
href: "href",
hash: "hash"
}
}));
I tried a similar test, and it worked with me...
My code:
export const Blah = () => {
const BLAH = 'https://www.google.com/'
const handleBlah = () => {
window.open(BLAH, '_blank')
}
return (
<button onClick={handleBlah}> BLAHBLAH </button>
)
}
My test using Jest:
it('should be able to render "BLAHBLAH " button ', () => {
window.open = jest.fn();
const BLAH = 'https://www.google.com/'
const { getByText } = render(<Blah/>) // Get text by my page Blah
const buttonGoToBlah = getByText('BLAHBLAH') // Get button by text
fireEvent.click(buttonGoToBlah) // Simulate the click event
expect(window.open).toHaveBeenCalledTimes(1) // Expect the window.open have to been called at least once.
expect(window.open).toHaveBeenCalledWith(BLAH, '_blank'); // And the page should be the same called in my BLAH page
})

Categories

Resources