Can not use CSS modules in Nextjs, Ant Design? - less

I'm doing a NextJS project using Ant design, Less. But I can't use CSS modules with Less even when I add
cssModules: true,
Here my next.config.js
const withPlugins = require("next-compose-plugins");
const withLess = require('#zeit/next-less')
const lessToJS = require('less-vars-to-js')
const fs = require('fs')
const path = require('path')
// Where your antd-custom.less file lives
const themeVariables = lessToJS(
fs.readFileSync(path.resolve(__dirname, './assets/antd-custom.less'), 'utf8')
)
module.exports = withLess({
cssModules: true,
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables, // make your antd custom effective
},
webpack: (config, { isServer }) => {
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/
const origExternals = [...config.externals]
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback()
if (typeof origExternals[0] === 'function') {
origExternals[0](context, request, callback)
} else {
callback()
}
},
...(typeof origExternals[0] === 'function' ? [] : origExternals),
]
config.module.rules.unshift({
test: antStyles,
use: 'null-loader',
})
}
return config
},
})
index.js:
import styles from 'path-to-less.less'
<p className={styles.styleTab1} >Conntents </p>
but I it doesn't effect to my component.

Looks like this is a solution:
https://github.com/vercel/next.js/issues/8156#issuecomment-516009764
From my tries, this solution requires #zeit/next-less, #zeit/next-css, less, less-loader as dependencies 🤷🏽‍♂️.

Related

React native couldn't resolve local module after noHoist has been added to project

I have this monorepo js setup with yarn workspaces and lerna
/package.json
/packages
/common (js shared code)
/package.json
/mobile (react native - metro)
/package.json
/web (CRA)
/package.json
Mobile and web packages are importing common package inside package.json as follow
"dependencies": {
"common": "*",
}
I had to add noHoist option in root package.json so that mobile native dependencies don't get hoisted so build scripts still run fine
"workspaces": {
"packages": [
"packages/*"
],
"nohoist": [
"**/react-native",
"**/react-native/**"
]
}
Web did work fine before and after adding noHoist option
React native metro bundling start failing after adding noHoist .. it shows
"Error: Unable to resolve module .. could not be found within the project or in these directories:
node_modules
../../node_modules"
However common package does actually exists under root node_modules ?
Looks like some kind of a linking issue ! (did try to link it manually/ same issue) .. note that I didn't add common package under noHoist
here how my metro config looks like
const path= require('path');
const watchFolders = [
path.resolve(`${__dirname}`), // Relative path to package node_modules
path.resolve(`${__dirname}/../../node_modules`), // Relative path to root node_modules ];
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),},
maxWorkers: 2,
watchFolders, };
ANY IDEA ? 🧐
Turns out the issue was in bundling, fixed by editing metro.config.js to include blocklist and extraNodeModules
const path = require('path');
const exclusionList = require('metro-config/src/defaults/exclusionList');
const getWorkspaces = require('get-yarn-workspaces');
function generateAssetsPath(depth, subpath) {
return `/assets`.concat(
Array.from({ length: depth })
// eslint-disable-next-line no-unused-vars
.map((_, i) => `/${subpath}`)
.join(''),
);
}
function getMetroAndroidAssetsResolutionFix(params = {}) {
const { depth = 3 } = params;
let publicPath = generateAssetsPath(depth, 'dir');
const applyMiddleware = (middleware) => (req, res, next) => {
// eslint-disable-next-line no-plusplus
for (let currentDepth = depth; currentDepth >= 0; currentDepth--) {
const pathToReplace = generateAssetsPath(currentDepth, 'dir');
const replacementPath = generateAssetsPath(depth - currentDepth, '..');
if (currentDepth === depth) {
publicPath = pathToReplace;
}
if (req.url.startsWith(pathToReplace)) {
req.url = req.url.replace(pathToReplace, replacementPath);
break;
}
}
return middleware(req, res, next);
};
return {
publicPath,
applyMiddleware,
};
}
function getNohoistedPackages() {
// eslint-disable-next-line global-require
const monorepoRootPackageJson = require('../../package.json');
const nohoistedPackages = monorepoRootPackageJson.workspaces.nohoist
.filter((packageNameGlob) => !packageNameGlob.endsWith('**'))
.map((packageNameGlob) => packageNameGlob.substring(3));
return nohoistedPackages;
}
function getMetroNohoistSettings({
dir,
workspaceName,
reactNativeAlias,
} = {}) {
const nohoistedPackages = getNohoistedPackages();
const blockList = [];
const extraNodeModules = {};
nohoistedPackages.forEach((packageName) => {
extraNodeModules[packageName] =
reactNativeAlias && packageName === 'react-native'
? path.resolve(dir, `./node_modules/${reactNativeAlias}`)
: path.resolve(dir, `./node_modules/${packageName}`);
const regexSafePackageName = packageName.replace('/', '\\/');
blockList.push(
new RegExp(
`^((?!${workspaceName}).)*\\/node_modules\\/${regexSafePackageName}\\/.*$`,
),
);
});
return { extraNodeModules, blockList };
}
const workspaces = getWorkspaces(__dirname);
const androidAssetsResolutionFix = getMetroAndroidAssetsResolutionFix({
depth: 3,
});
const nohoistSettings = getMetroNohoistSettings({
dir: __dirname,
workspaceName: 'mobile',
});
module.exports = {
transformer: {
// Apply the Android assets resolution fix to the public path...
// publicPath: androidAssetsResolutionFix.publicPath,
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
// server: {
// // ...and to the server middleware.
// enhanceMiddleware: (middleware) =>
// androidAssetsResolutionFix.applyMiddleware(middleware),
// },
// Add additional Yarn workspace package roots to the module map.
// This allows importing importing from all the project's packages.
watchFolders: [
path.resolve(__dirname, '../../node_modules'),
...workspaces.filter((workspaceDir) => !(workspaceDir === __dirname)),
],
maxWorkers: 2,
resolver: {
// Ensure we resolve nohoisted packages from this directory.
blockList: exclusionList(nohoistSettings.blockList),
extraNodeModules: nohoistSettings.extraNodeModules,
},
};
You can check this universal CRA/RN mono-repo that uses such metro configs

react native environment variables .env return undefined

I am currently using dotenv but there seems to be some caching issue with the #env. So wanted to try using process.env but it returns undefined. I am using expo, dotenv and webpack.
On app.js process.env.REACT_APP_KEY returns undefined, already restarted server, terminal and even my PC.
.env
REACT_APP_KEY=aaddddawrfffvvvvssaa
REACT_APP_KEY = aaddddawrfffvvvvssa
Webpack config
const createExpoWebpackConfigAsync = require('#expo/webpack-config');
module.exports = async function (env, argv) {
const config = await createExpoWebpackConfigAsync(env, argv);
const path = require('path')
config.module.rules = config.module.rules.map(rule => {
if (rule.oneOf) {
let hasModified = false;
const newRule = {
...rule,
oneOf: rule.oneOf.map(oneOfRule => {
if (oneOfRule.use && oneOfRule.use.loader && oneOfRule.use.loader.includes('babel-loader')) {
oneOfRule.include = [
path.resolve('.'),
path.resolve('node_modules/#ui-kitten/components'),
]
}
if (oneOfRule.test && oneOfRule.test.toString().includes('svg')) {
hasModified = true;
const test = oneOfRule.test.toString().replace('|svg', '');
return {...oneOfRule, test: new RegExp(test)};
} else {
return oneOfRule;
}
})
};
// Add new rule to use svgr
// Place at the beginning so that the default loader doesn't catch it
if (hasModified) {
newRule.oneOf.unshift({
test: /\.svg$/,
exclude: /node_modules/,
use: [
{
loader: '#svgr/webpack',
}
]
});
}
return newRule;
} else {
return rule;
}
});
return config;
};
babel config
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
'react-native-reanimated/plugin',
['module:react-native-dotenv', {
'moduleName': '#env',
'path': '.env',
"blocklist": null,
"allowlist": null,
"safe": true,
"allowUndefined": false,
}]
],
};
};
If it matters (for dotenv)
declare module '#env' {
export const API_ENDPOINT: string;
}
Also tried process.env.NODE_ENV (which is working and prints "development" as output). Only process.env.VARIABLE_NAME is undefined
Maintainer here! process.env support in react-native-dotenv was just added this month https://github.com/goatandsheep/react-native-dotenv/issues/187

Removing all data-test attributes from Vue templates during production build in Vue 3

I work with Vue3 in TS (last vue-cli).
I want to get all nodes (vnodes) elements when vue-loader compile .vue file.
I need to read nodes attributes and remove all "data-test".
I have try in vue.config.js to use :
module.exports = {
chainWebpack: (config) => {
config.module
.rule('vue')
.use('vue-loader')
// .loader('vue-loader') // same with
.tap((options) => {
options.compilerOptions = {
...(options.compilerOptions || {}),
modules: [ // never enter here
{
preTransformNode(node) {
// if (process.env.NODE_ENV === 'production') {
const { attrsMap, attrsList } = node
console.log(node)
if (attrsMap['qa-id']) {
delete attrsMap['qa-id']
const index = attrsList.findIndex(
(x) => x.name === 'data-test'
)
attrsList.splice(index, 1)
}
// }
return node
}
}
]
}
return options
})
}
}
I know the transformation is done inside vue-template-compiler.
How can I enter in compile hook ?
I have try to use preTransformNode in module but that fail.
Sources :
https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#readme
https://vue-loader.vuejs.org/options.html
The main problem here is that you are working with vue-template-compiler documentation, but that package is the compiler for Vue 2!
In Vue 3, compiler is split into multiple packages and is missing proper documentation as of now (or I was just unable to find it)
Also there were significant changes in the API - instead of modules, you pass nodeTransforms (source) and transforms are not objects, just functions.
Luckily for you, there is a interesting video on YT presented by Vue core member Rahul Kadyan which shows the exact use case you need (removing data-test attributes) - code
So I guess the code should look like this:
function removeDataTestAttrs(node) {
if (node.type === 1 /* NodeTypes.ELEMENT */) {
node.props = node.props.filter(prop =>
prop.type === 6 /* NodeTypes.ATTRIBUTE */
? prop.name !== 'data-test'
: true
)
}
}
module.exports = {
parallel: false, // !!IMPORTANT!! - see note below
chainWebpack: (config) => {
config.module
.rule('vue')
.use('vue-loader')
.tap((options) => {
options.compilerOptions = {
...(options.compilerOptions || {}),
nodeTransforms: [removeDataTestAttrs]
}
return options
})
}
}
Note - the problem mentioned in comments (solution working with serve but throws errors on build) is caused by Vue CLI using thread-loader for production builds. The problem is that while using thread-loader, you can not pass a functions as part of Webpack config (see this warning in the docs) so setting parralel: false is required to make it work....
Vite (Update - 22.06.22)
// vite.config.ts
function removeDataTestAttrs(node) {
if (node.type === 1 /* NodeTypes.ELEMENT */) {
node.props = node.props.filter(prop =>
prop.type === 6 /* NodeTypes.ATTRIBUTE */
? prop.name !== 'data-test'
: true
)
}
}
export default defineConfig(() => {
return {
plugins: [
vue({
template: {
compilerOptions: {
nodeTransforms: isProd ? [removeDataTestAttrs] : [],
},
},
}),
]
}
})
Vue-CLI 5 + Vue 3.2:
const { defineConfig } = require('#vue/cli-service');
function removeAttributesDuringBuild (node) {
const attributesToRemove = [
'data-test',
':data-test',
'v-bind:data-test',
'data-value',
':data-value',
'v-bind:data-value'
];
const nodeIsElement = node.type === 1; // ENUMS ARE STUPID
if (nodeIsElement) {
node.props = node.props.filter(function (prop) {
const propIsAttribute = prop.type === 6; // ENUMS ARE STUPID
const propIsDynamicAttribute = prop.name === 'bind';
if (propIsAttribute) {
const attributeName = prop.name;
return !attributesToRemove.includes(attributeName);
}
if (propIsDynamicAttribute) {
const attributeName = prop.arg?.content;
return !attributesToRemove.includes(attributeName);
}
return true;
});
}
}
module.exports = defineConfig({
lintOnSave: false,
transpileDependencies: true,
parallel: false, // disabled to allow for node transforms
chainWebpack: (config) => {
// Remove comments during build
config.optimization
.minimizer('terser')
.tap((args) => {
args[0].terserOptions.output = {
...args[0].terserOptions.output,
comments: false
};
return args;
});
// Remove dev attributes
config.module
.rule('vue')
.use('vue-loader')
.tap(function (options) {
options.compilerOptions = {
...(options.compilerOptions || {}),
nodeTransforms: [removeAttributesDuringBuild]
};
return options;
});
}
});
Vite 4 + Vue 2.7
import vue from '#vitejs/plugin-vue2';
import { defineConfig } from 'vite';
function removeAttributesDuringBuild (astEl) {
const attributesToRemove = [
'data-test',
':data-test',
'v-bind:data-test',
'data-value',
':data-value',
'v-bind:data-value'
];
function removeAttribute (attributesMap, attributesList, attributeToRemove) {
if (attributesMap[attributeToRemove]) {
delete attributesMap[attributeToRemove];
const index = attributesList.findIndex(function (attribute) {
return attribute.name === attributeToRemove;
});
attributesList.splice(index, 1);
}
}
if (process.env.NODE_ENV === 'production') {
const { attrsMap, attrsList } = astEl;
attributesToRemove.forEach(function (attributeToRemove) {
removeAttribute(attrsMap, attrsList, attributeToRemove);
});
}
return astEl;
}
export default defineConfig(() => {
return {
plugins: [
vue({
template: {
compilerOptions: {
modules: [
{
preTransformNode: removeAttributesDuringBuild
}
]
}
}
})
]
};
});

NextJS polyfills not loaded before other JS

I am using https://github.com/zeit/next.js/ and had a look at the examples:
https://github.com/zeit/next.js/tree/canary/examples/with-ant-design-less
https://github.com/zeit/next.js/tree/canary/examples/with-redux
https://github.com/zeit/next.js/tree/canary/examples/with-polyfills
I merged the three projects, so that I can use ant design and redux together with polyfill.
Works so far in Chrome, but it seems that the polyfills are not loaded correctly now.
My next.config.js looks like this:
/* eslint-disable */
const withLess = require("#zeit/next-less");
const lessToJS = require("less-vars-to-js");
const fs = require("fs");
const path = require("path");
// Where your antd-custom.less file lives
const themeVariables = lessToJS(
fs.readFileSync(path.resolve(__dirname, "./assets/antd-custom.less"), "utf8")
);
module.exports = withLess({
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables // make your antd custom effective
},
webpack: (config, {
isServer,
defaultLoaders
}) => {
const originalEntry = config.entry;
config.entry = async() => {
const entries = await originalEntry();
if (
entries["main.js"] &&
!entries["main.js"].includes("./polyfills.js")
) {
entries["main.js"].unshift("./polyfills.js");
}
return entries;
};
config.module.rules.push({
test: /\.scss$/,
use: [
defaultLoaders.babel,
{
loader: require("styled-jsx/webpack").loader,
options: {
type: "scoped",
javascriptEnabled: true
}
},
"sass-loader"
]
});
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === "function") {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === "function" ? [] : origExternals)
];
config.module.rules.unshift({
test: antStyles,
use: "null-loader"
});
}
return config;
}
});
My .eslintrc.js looks like this:
module.exports = {
extends: ["airbnb"],
env: {
browser: true
},
parser: "babel-eslint",
rules: {
indent: 0,
"comma-dangle": [
2,
{
arrays: "always-multiline",
objects: "always-multiline",
imports: "always-multiline",
exports: "always-multiline",
functions: "ignore"
}
],
"max-len": 1,
"arrow-parens": 0,
"import/no-named-as-default": 0,
"import/no-extraneous-dependencies": 0,
"no-nested-ternary": 0,
"no-use-before-define": 0,
"react/jsx-props-no-spreading": 0,
"react/prop-types": 1,
"react/no-array-index-key": 1,
"react/no-did-mount-set-state": 0,
"jsx-a11y/label-has-for": [
2,
{
components: ["Label"],
required: {
some: ["nesting", "id"]
},
allowChildren: true
}
],
"jsx-a11y/click-events-have-key-events": 1,
"jsx-a11y/no-noninteractive-element-interactions": 1,
"jsx-a11y/anchor-is-valid": 1,
"jsx-a11y/no-static-element-interactions": 1
}
};
My polyfills.js:
/* eslint no-extend-native: 0 */
// core-js comes with Next.js. So, you can import it like below
import includes from 'core-js/library/fn/string/virtual/includes';
import repeat from 'core-js/library/fn/string/virtual/repeat';
import assign from 'core-js/library/fn/object/assign';
// Add your polyfills (from IE10 is supported by default)
// This files runs at the very beginning (even before React and Next.js core)
String.prototype.includes = includes;
String.prototype.repeat = repeat;
Object.assign = assign;
In IE11 I get:
Object doesn't support property or method 'includes'
Can someone help here ?
I think the one you are missing is actually Array.includes.
I am using nextjs, with core-js#3, and in my polyfills I had to add
import 'core-js/features/object/values';
import 'core-js/features/object/entries';
import 'core-js/features/object/get-own-property-symbols';
import 'core-js/features/array/includes';
after these, I was able to make it work on IE11.

How to mock window.location.href with Jest + Vuejs?

Currently, I am implementing unit tests for my project and there is a file that contains window.location.href.
I want to mock this to test and here is my sample code:
it("method A should work correctly", () => {
const url = "http://dummy.com";
Object.defineProperty(window.location, "href", {
value: url,
writable: true
});
const data = {
id: "123",
name: null
};
window.location.href = url;
wrapper.vm.methodA(data);
expect(window.location.href).toEqual(url);
});
But I get this error:
TypeError: Cannot redefine property: href
at Function.defineProperty (<anonymous>)
How should I resolve it?
You can try:
global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
value: {
href: url
}
});
expect(window.location.href).toEqual(url);
Have a look at the Jest Issue for that problem:
Jest Issue
2020 Update
Basic
The URL object has a lot of the same functionality as the Location object. In other words, it includes properties such as pathname, search, hostname, etc. So for most cases, you can do the following:
delete window.location
window.location = new URL('https://www.example.com')
Advanced
You can also mock Location methods that you might need, which don't exist on the URL interface:
const location = new URL('https://www.example.com')
location.assign = jest.fn()
location.replace = jest.fn()
location.reload = jest.fn()
delete window.location
window.location = location
I have resolved this issue by adding writable: true and move it to beforeEach
Here is my sample code:
global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, "location", {
value: {
href: url
},
writable: true
});
Solution for 2019 from GitHub:
delete global.window.location;
global.window = Object.create(window);
global.window.location = {
port: '123',
protocol: 'http:',
hostname: 'localhost',
};
The best is probably to create a new URL instance, so that it parses your string like location.href does, and so it updates all the properties of location like .hash, .search, .protocol etc.
it("method A should work correctly", () => {
const url = "http://dummy.com/";
Object.defineProperty(window, "location", {
value: new URL(url)
} );
window.location.href = url;
expect(window.location.href).toEqual(url);
window.location.href += "#bar"
expect(window.location.hash).toEqual("#bar");
});
https://repl.it/repls/VoluminousHauntingFunctions
Many of the examples provided doesn't mock the properties of the original Location object.
What I do is just replace Location object (window.location) by URL, because URL contains the same properties as Location object like "href", "search", "hash", "host".
Setters and Getters also work exactly like the Location object.
Example:
const realLocation = window.location;
describe('My test', () => {
afterEach(() => {
window.location = realLocation;
});
test('My test func', () => {
// #ts-ignore
delete window.location;
// #ts-ignore
window.location = new URL('http://google.com');
console.log(window.location.href);
// ...
});
});
Working example with #testing-library/react in 2020 for window.location.assign:
afterEach(cleanup)
beforeEach(() => {
Object.defineProperty(window, 'location', {
writable: true,
value: { assign: jest.fn() }
})
})
Extending #jabacchetta's solution to avoid this setting bleeding into other tests:
describe("Example", () => {
let location;
beforeEach(() => {
const url = "https://example.com";
location = window.location;
const mockLocation = new URL(url);
mockLocation.replace = jest.fn();
delete window.location;
window.location = mockLocation;
});
afterEach(() => {
window.location = location;
});
});
How to reassign window.location in your code base; the simplest working setup we found for our Jest tests:
const realLocation = window.location;
beforeEach(() => {
delete window.location;
});
afterEach(() => {
window.location = realLocation;
});
you can try jest-location-mock.
npm install --save-dev jest-location-mock
update jest configs at jest.config.js file or jest prop inside package.json:
setupFilesAfterEnv: [ "./config/jest-setup.js" ]
create jest-setup.js
import "jest-location-mock";
usage:
it("should call assign with a relative url", () => {
window.location.assign("/relative-url");
expect(window.location).not.toBeAt("/");
expect(window.location).toBeAt("/relative-url");
});
You can try a helper:
const setURL = url => global.jsdom.reconfigure({url});
describe('Test current location', () => {
test('with GET parameter', () => {
setURL('https://test.com?foo=bar');
// ...your test here
});
});
This is valid for Jest + TypeScript + Next.js (in case you use useRoute().push
const oldWindowLocation = window.location;
beforeAll(() => {
delete window.location;
window.location = { ...oldWindowLocation, assign: jest.fn() };
});
afterAll(() => {
window.location = oldWindowLocation;
});
JSDOM Version
Another method, using JSDOM, which will provide window.location.href and all of the other properties of window.location, (e.g. window.location.search to get query string parameters).
import { JSDOM } from 'jsdom';
...
const { window } = new JSDOM('', {
url: 'https://localhost/?testParam=true'
});
delete global.window;
global.window = Object.create(window);
I could not find how to test that window.location.href has been set with correct value AND test that window.location.replace() has been called with right params, but I tried this and it seems perfect.
const mockWindowLocationReplace = jest.fn()
const mockWindowLocationHref = jest.fn()
const mockWindowLocation = {}
Object.defineProperties(mockWindowLocation, {
replace: {
value: mockWindowLocationReplace,
writable: false
},
href : {
set: mockWindowLocationHref
}
})
jest.spyOn(window, "location", "get").mockReturnValue(mockWindowLocation as Location)
describe("my test suite", () => {
// ...
expect(mockWindowLocationReplace).toHaveBeenCalledWith('foo')
expect(mockWindowLocationHref).toHaveBeenCalledWith('bar')
})
Can rewrite window.location by delete this global in every test.
delete global.window.location;
const href = 'http://localhost:3000';
global.window.location = { href };
Based on examples above and in other threads, here is a concrete example using jest that might help someone:
describe('Location tests', () => {
const originalLocation = window.location;
const mockWindowLocation = (newLocation) => {
delete window.location;
window.location = newLocation;
};
const setLocation = (path) =>
mockWindowLocation(
new URL(`https://example.com${path}`)
);
afterEach(() => {
// Restore window.location to not destroy other tests
mockWindowLocation(originalLocation);
});
it('should mock window.location successfully', () => {
setLocation('/private-path');
expect(window.location.href).toEqual(
`https://example.com/private-path`
);
});
});
Probably irrelevant. But for those seeking a solution for window.open('url', attribute) I applied this, with help of some comments above:
window = Object.create(window);
const url = 'https://www.9gag.com';
Object.defineProperty(window, 'open', { value: url });
expect(window.open).toEqual(url);
Here's a simple one you can use in a beforeEach or ala carte per test.
It utilizes the Javascript window.history and its pushState method to manipulate the URL.
window.history.pushState({}, 'Enter Page Title Here', '/test-page.html?query=value');
I use the following way using the Jest's mocking mechanism (jest.spyOn()) instead of directly overwriting the object property.
describe("...", () => {
beforeEach(() => {
const originalLocation = window.location;
jest.spyOn(window, "location", "get").mockImplementation(() => ({
...originalLocation,
href: "http://dummy.com", // Mock window.location.href here.
}))
});
afterEach(() => {
jest.restoreAllMocks()
});
it("...", () => {
// ...
})
});
I learned it from this post.