Jest URL.createObjectURL is not a function - javascript

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

Related

ES6 imports and 'is not a constructor' in Jest.mock

Similar to Jest TypeError: is not a constructor in Jest.mock, except I am using ES6 imports - and the answer given to that question is not working on my situation.
Following the Jest .mock() documentation I am attempting to mock the constructor Client from the pg module.
I have a constructor, Client, imported from an ES6 module called pg. Instances of Client should have a query method.
import { Client } from "pg";
new Client({ connectionString: 'postgresql://postgres:postgres#localhost:5432/database' });
export async function doThing(client): Promise<string[]> {
var first = await client.query('wooo')
var second = await client.query('wooo')
return [first, second]
}
Here's my __tests__/test.ts
const log = console.log.bind(console)
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
import { Client } from "pg";
import { doThing } from "../index";
it("works", async () => {
let client = new Client({});
var result = await doThing(client);
expect(result).toBe(['one', 'two'])
});
This is similar to the answer given in Jest TypeError: is not a constructor in Jest.mock, but it's failing here.
The code, just:
const mockDbClient = new Client({ connectionString: env.DATABASE_URL });
fails with:
TypeError: pg_1.Client is not a constructor
I note the docs mention __esModule: true is required when using default exports, but Client is not a default export from pg (I've checked).
How can I make the constructor work properly?
Some additional notes after getting an answer
Here's a slightly longer-form version of the answer, with comments about what's happening on each line - I hope people reading this find it useful!
jest.mock("pg", () => {
// Return the fake constructor function we are importing
return {
Client: jest.fn().mockImplementation(() => {
// The consturctor function returns various fake methods
return {
query: jest.fn()
.mockReturnValueOnce(firstResponse)
.mockReturnValueOnce(secondResponse),
connect: jest.fn()
}
})
}
})
When you mock the module, it needs to have the same shape as the actual module. Change:
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
...to:
jest.mock("pg", () => ({
Client: jest.fn().mockImplementation(() => ({
query: jest.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two')
}))
}));

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

Proxyquire shows error "Cannot find module"

I'm trying to use proxyquire to replace a private function for testing in my Meteor app.
Meteor 1.6.1
meteortesting:mocha#1.1.2
In my parentFunction.js:
import { some function } from 'anotherFile';
function childFunction() {
...
return someValue;
}
export default function parentFunction() {
return childFunction()
}
In my test file:
const proxyquire = require('proxyquire');
if (Meteor.isServer) {
...
describe('parentFunction', () => {
it('uses the mocked child function', () => {
const testThing = proxyquire('./parentFunction', {
'childFunction': () => ({ 'name': 'bob' }),
});
});
}
parentFunction.js is in the same folder as my test file, and just to double check the path, I made sure this works:
import parentFunction from './parentFunction';
But when I run the test, I'm seeing an error:
Error: Cannot find module './parentFunction.js'
What am I doing wrong? I've tried an absolute path, that didn't work. And as far as I can see from the documentation a relative path in the file where proxiquire is required, should be fine.
Thanks for any help!

How to clear a module mock between tests in same test suite in Jest?

I've mocked some nodejs modules (one of them, for example, is fs). I have them in a __mocks__ folder (same level als node_modules) folder and the module mocking works. However, whichever "between test clearing" option I use, the next test is not "sandboxed". What is going wrong here?
A very simplified example of the mocked fs module is:
// __mocks__/fs.js
module.exports = {
existsSync: jest.fn()
.mockReturnValueOnce(1)
.mockReturnValueOnce(2)
.mockReturnValueOnce(3)
}
I'm simply expecting that in every test, whenever init() is called (see below), existsSync starts again at value 1: the first value of jest.fn().mockReturnValue(). In the testfile I have the following structure:
// init.test.js
const init = require("../init");
const { existsSync } = require("fs");
jest.mock("fs");
describe("initializes script", () => {
afterEach(() => {
// see below!
});
test("it checks for a package.json in current directory", () => {
init();
});
test("it stops script if there's a package.json in dir", () => {
init(); // should be run in clean environment!
});
}
And once again very simplified, the init.js file
const { existsSync } = require("fs");
console.log("value of mocked response : ", existsSync())
I'm getting the following results for existsSync() after the first and second run ofinit() respectively when I run in afterEach():
jest.resetModules() : 1, 2
existsSync.mockReset(): 1, undefined
existsSync.mockClear(): 1, 2
existsSync.mockRestore(): 1, undefined
Somebody know what I'am doing wrong? How do I clear module mock between tests in the same suite? I'll glady clarify if necessary. Thanks!
Reset the modules and require them again for each test:
describe("initializes script", () => {
afterEach(() => {
jest.resetModules()
});
beforeEach(() => {
jest.mock("fs");
})
test("it checks for a package.json in current directory", () => {
const init = require("../init");
init();
});
test("it stops script if there's a package.json in dir", () => {
const init = require("../init");
init();
});
}
I had problems with the solution above. I managed to solve the issue with the next snippet.
afterEach(() => {
Object.keys(mockedModule).forEach(method => mockedModule[method].mockReset())
})
I would prefer to have a native method doing this though. Something like mockedModule.mockReset().
For local variables, the scope of declaration is important.
const mockFunc1 = jest.fn() // possibly bad mock reset/clear between tests
describe('useGetMetaData', () => {
const mockFunc2 = jest.fn() // good mock reset/clear between tests
afterEach(() => {/* reset/clear mocks */})
test.todo('implement tests here')
})

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