From 2c61b0206a7d8687d08b9e46ee8acbc3993238f4 Mon Sep 17 00:00:00 2001 From: dominikg Date: Fri, 4 Mar 2022 17:41:12 +0100 Subject: [PATCH] test: add unit test for define plugin --- .../src/node/__tests__/plugins/define.spec.ts | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 packages/vite/src/node/__tests__/plugins/define.spec.ts diff --git a/packages/vite/src/node/__tests__/plugins/define.spec.ts b/packages/vite/src/node/__tests__/plugins/define.spec.ts new file mode 100644 index 00000000000000..9a65f8f3a51cea --- /dev/null +++ b/packages/vite/src/node/__tests__/plugins/define.spec.ts @@ -0,0 +1,39 @@ +import { definePlugin } from '../../plugins/define' +import { resolveConfig } from '../../config' + +async function createDefinePluginTransform( + define: Record = {}, + build = true, + ssr = false +) { + const config = await resolveConfig({ define }, build ? 'build' : 'serve') + const instance = definePlugin(config) + return async (code: string) => { + const result = await instance.transform.call({}, code, 'foo.ts', { ssr }) + return result?.code || result + } +} + +describe('definePlugin', () => { + test('replaces custom define', async () => { + const transform = await createDefinePluginTransform({ + __APP_VERSION__: JSON.stringify('1.0') + }) + expect(await transform('const version = __APP_VERSION__ ;')).toBe( + 'const version = "1.0" ;' + ) + expect(await transform('const version = __APP_VERSION__;')).toBe( + 'const version = "1.0";' + ) + }) + + test('replaces import.meta.env.SSR with false', async () => { + const transform = await createDefinePluginTransform() + expect(await transform('const isSSR = import.meta.env.SSR ;')).toBe( + 'const isSSR = false ;' + ) + expect(await transform('const isSSR = import.meta.env.SSR;')).toBe( + 'const isSSR = false;' + ) + }) +})