From 7082744f7edc79ab4e583d88428beea5aba900ee Mon Sep 17 00:00:00 2001 From: Nicholas Cunningham Date: Wed, 25 Oct 2023 10:39:33 -0600 Subject: [PATCH] fix(js): should respect vitest test environment closes: #19853 --- .../js/src/generators/library/library.spec.ts | 28 +++++++++++++++++++ packages/js/src/generators/library/library.ts | 2 ++ packages/vite/src/utils/generator-utils.ts | 2 +- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/js/src/generators/library/library.spec.ts b/packages/js/src/generators/library/library.spec.ts index 969bf03c7c1214..27ec711efdd61a 100644 --- a/packages/js/src/generators/library/library.spec.ts +++ b/packages/js/src/generators/library/library.spec.ts @@ -1359,4 +1359,32 @@ describe('lib', () => { expect(tree.exists('web/my-lib/src/lib/my-lib.ts')).toBeTruthy(); }); }); + + describe('--testEnvironment', () => { + it('should generate a vite config with testEnvironment set to node', async () => { + await libraryGenerator(tree, { + ...defaultOptions, + name: 'my-node-lib', + unitTestRunner: 'vitest', + testEnvironment: 'node', + }); + + const content = tree.read('my-node-lib/vite.config.ts', 'utf-8'); + + expect(content).toContain(`environment: 'node'`); + }); + + it('should generate a vite config with testEnvironment set to jsdom by default', async () => { + await libraryGenerator(tree, { + ...defaultOptions, + name: 'my-jsdom-lib', + unitTestRunner: 'vitest', + testEnvironment: undefined, + }); + + const content = tree.read('my-jsdom-lib/vite.config.ts', 'utf-8'); + + expect(content).toContain(`environment: 'jsdom'`); + }); + }); }); diff --git a/packages/js/src/generators/library/library.ts b/packages/js/src/generators/library/library.ts index 89dcea84710d6c..de881c2f002a46 100644 --- a/packages/js/src/generators/library/library.ts +++ b/packages/js/src/generators/library/library.ts @@ -99,6 +99,7 @@ export async function libraryGeneratorInternal( project: options.name, includeLib: true, includeVitest: options.unitTestRunner === 'vitest', + testEnvironment: options.testEnvironment, }, false ); @@ -136,6 +137,7 @@ export async function libraryGeneratorInternal( project: options.name, includeLib: false, includeVitest: true, + testEnvironment: options.testEnvironment, }, true ); diff --git a/packages/vite/src/utils/generator-utils.ts b/packages/vite/src/utils/generator-utils.ts index a28c99c7e14bf7..af9094795d3e13 100644 --- a/packages/vite/src/utils/generator-utils.ts +++ b/packages/vite/src/utils/generator-utils.ts @@ -805,7 +805,7 @@ function handleViteConfigFileExists( cache: { dir: `${offsetFromRoot}node_modules/.vitest`, }, - environment: 'jsdom', + environment: `${options.testEnvironment ?? 'jsdom'}`, include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], };