Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/remove-testid/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test-results/
playwright-report/
8 changes: 8 additions & 0 deletions examples/remove-testid/app/components/Hello.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<template>
<h1
data-testid="hello"
data-test="world"
>
Hello Nuxt!
</h1>
</template>
5 changes: 5 additions & 0 deletions examples/remove-testid/app/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<template>
<div>
<Hello />
</div>
</template>
26 changes: 26 additions & 0 deletions examples/remove-testid/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const buildDir = process.env.FEATURE ? `./.nuxt/test/build-${process.env.FEATURE}` : undefined

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: ['@nuxt/test-utils/module'],
$env: {
custom: {
testUtils: {
removeTestIdAttribute: 'data-test',
},
},
},
$production: {
testUtils: {
removeTestIdAttribute: true,
},
},
devtools: false,
buildDir,
compatibilityDate: '2024-04-03',
nitro: {
output: {
dir: buildDir ? `${buildDir}/output` : undefined,
},
},
})
31 changes: 31 additions & 0 deletions examples/remove-testid/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "example-remove-testid",
"private": true,
"type": "module",
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"test": "pnpm run --sequential '/test:.*/'",
"test:vitest": "pnpm run build:feature && vitest run",
"test:playwright": "playwright test",
"build:feature": "pnpm run '/build:feature:.*/'",
"build:feature:enabled": "FEATURE=enabled nuxt build",
"build:feature:disabled": "FEATURE=disabled nuxt build --envName staging",
"build:feature:custom": "FEATURE=custom nuxt build --envName custom"
},
"dependencies": {
"nuxt": "4.6.3"
},
"devDependencies": {
"@nuxt/test-utils": "latest",
"@playwright/test": "1.64.1",
"@vue/test-utils": "2.5.1",
"happy-dom": "21.0.4",
"tinyglobby": "0.2.17",
"typescript": "6.0.3",
"vitest": "5.0.5"
}
}
24 changes: 24 additions & 0 deletions examples/remove-testid/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import process from 'node:process'
import { defineConfig, devices } from '@playwright/test'
import type { ConfigOptions } from '@nuxt/test-utils/playwright'

export default defineConfig<ConfigOptions>({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: 'html',
timeout: 120_000,
use: {
trace: 'on-first-retry',
nuxt: {
rootDir: import.meta.dirname,
},
},
projects: [
{
name: 'chromium-headless-shell',
use: { ...devices['Desktop Chrome'] },
},
],
})
15 changes: 15 additions & 0 deletions examples/remove-testid/test/e2e/build.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { fileURLToPath } from 'node:url'
import { expect, it } from 'vitest'
import { createPage, setup } from '@nuxt/test-utils/e2e'

await setup({
rootDir: fileURLToPath(new URL('../../', import.meta.url)),
browser: true,
})

it('should disable feature when building in tests', async () => {
const page = await createPage('/')
const text = await page.getByTestId('hello').textContent()
expect(text).toContain('Hello Nuxt!')
await page.close()
})
54 changes: 54 additions & 0 deletions examples/remove-testid/test/e2e/feature.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { createPage, setup } from '@nuxt/test-utils/e2e'

async function setupTest(fixtureName: string) {
await setup({
rootDir: fileURLToPath(new URL('../../', import.meta.url)),
build: false,
browser: true,
nuxtConfig: {
nitro: {
output: {
dir: fileURLToPath(new URL(`../../.nuxt/test/${fixtureName}/output`, import.meta.url)),
},
},
},
})
}

describe('feature enabled build', async () => {
await setupTest('build-enabled')

it('should remove default test attribute when enabled', async () => {
const page = await createPage('/')
const heading = page.getByRole('heading', { level: 1 })
await expect(heading.isVisible()).resolves.toBeTruthy()
await expect(heading.getAttribute('data-testid')).resolves.toBeFalsy()
await expect(heading.getAttribute('data-test')).resolves.toBe('world')
})
})

describe('feature disabled build', async () => {
await setupTest('build-disabled')

it('should keep test attributes when disabled', async () => {
const page = await createPage('/')
const heading = page.getByRole('heading', { level: 1 })
await expect(heading.isVisible()).resolves.toBeTruthy()
await expect(heading.getAttribute('data-testid')).resolves.toBe('hello')
await expect(heading.getAttribute('data-test')).resolves.toBe('world')
})
})

describe('feature custom build', async () => {
await setupTest('build-custom')

it('should remove custom test attribute when enabled', async () => {
const page = await createPage('/')
const heading = page.getByRole('heading', { level: 1 })
await expect(heading.isVisible()).resolves.toBeTruthy()
await expect(heading.getAttribute('data-testid')).resolves.toBe('hello')
await expect(heading.getAttribute('data-test')).resolves.toBeFalsy()
})
})
10 changes: 10 additions & 0 deletions examples/remove-testid/test/nuxt/Hello.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'

import { Hello } from '#components'

it('should disable feature in unit tests', async () => {
const wrapper = await mountSuspended(Hello)
expect(wrapper.attributes('data-testid')).toBe('hello')
expect(wrapper.attributes('data-test')).toBe('world')
})
6 changes: 6 additions & 0 deletions examples/remove-testid/tests/build.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expect, test } from '@nuxt/test-utils/playwright'

test('should disable feature when building in tests', async ({ page, goto }) => {
await goto('/', { waitUntil: 'hydration' })
await expect(page.getByTestId('hello')).toHaveText('Hello Nuxt!')
})
17 changes: 17 additions & 0 deletions examples/remove-testid/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
]
}
21 changes: 21 additions & 0 deletions examples/remove-testid/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { defineConfig } from 'vitest/config'
import { defineVitestProject } from '@nuxt/test-utils/config'

export default defineConfig({
test: {
projects: [
{
test: {
name: 'e2e',
dir: './test/e2e',
},
},
await defineVitestProject({
test: {
name: 'nuxt',
dir: './test/nuxt',
},
}),
],
},
})
28 changes: 28 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isCI } from 'std-env'

import { setupImportMocking } from './module/mock.ts'
import { NuxtRootStubPlugin } from './module/plugins/entry.ts'
import { removeAttrsNodeTransform } from './module/plugins/remove-attrs.ts'
import { runInstallWizard } from './module/install-wizard.ts'
import { loadKit, resolveH3Package } from './utils.ts'
import { setupDevTools } from './devtools.ts'
Expand All @@ -17,6 +18,30 @@ export interface NuxtVitestOptions {
startOnBoot?: boolean
logToConsole?: boolean
vitestConfig?: VitestConfig
/**
* Remove testId attribute (case-insensitive) from Vue `<template>` at compile time.
* - `true`: remove `data-testid`
* - `string`: pass an attribute name to remove.
* - `false`: disable this feature.
*
* @example
* ```ts
* // nuxt.config.ts
* export default defineNuxtConfig({
* modules: ['@nuxt/test-utils/module'],
* $production: {
* testUtils: {
* // Remove `data-testid` in production builds
* removeTestIdAttribute: true,
* // Or specify custom attribute
* // removeTestIdAttribute: 'data-cy',
* },
* },
* })
* ```
* @default false
*/
removeTestIdAttribute?: boolean | string
/** @internal */
_fromVitestConfig?: boolean
}
Expand All @@ -30,6 +55,7 @@ export default defineNuxtModule<NuxtVitestOptions>({
defaults: {
startOnBoot: false,
logToConsole: false,
removeTestIdAttribute: false,
},
async onInstall(nuxt) {
await runInstallWizard(nuxt)
Expand Down Expand Up @@ -110,6 +136,25 @@ export default defineNuxtModule<NuxtVitestOptions>({
}
})

// Remove testId attribute
if (options.removeTestIdAttribute) {
const testIdAttr = options.removeTestIdAttribute === true ? 'data-testid' : options.removeTestIdAttribute
const transform = removeAttrsNodeTransform([testIdAttr])
logger.info(`Remove testIdAttribute '${testIdAttr}' enabled.`)
nuxt.hook('build:before', () => {
const template = (nuxt.options.vite.vue ||= {}).template ||= {}
template.compilerOptions = {
...template.compilerOptions,
nodeTransforms: [...template.compilerOptions?.nodeTransforms || [], transform],
}
const loader = nuxt.options.webpack.loaders.vue
loader.compilerOptions = {
...loader.compilerOptions,
nodeTransforms: [...loader.compilerOptions?.nodeTransforms || [], transform],
}
})
}

if (!nuxt.options.dev) return

// the nuxt instance is used by a standalone Vitest env, we skip this module
Expand Down
43 changes: 43 additions & 0 deletions src/module/plugins/remove-attrs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { CompilerOptions } from '@vue/compiler-sfc'

type NodeTransform = NonNullable<CompilerOptions['nodeTransforms']>[number]

const NodeTypes = {
ELEMENT: 1,
SIMPLE_EXPRESSION: 4,
ATTRIBUTE: 6,
DIRECTIVE: 7,
} as const

const ElementTypes = {
SLOT: 2,
} as const

export function removeAttrsNodeTransform(attrs: string[]): NodeTransform {
const attrNames = attrs.map(s => s.toLowerCase())
return (node) => {
if (node.type !== NodeTypes.ELEMENT || node.tagType === ElementTypes.SLOT) return

const { props } = node

for (let i = props.length - 1; i >= 0; i--) {
const prop = props[i]!

if (
(
prop.type === NodeTypes.ATTRIBUTE
&& attrNames.includes(prop.name.toLowerCase()))
|| (
prop.type === NodeTypes.DIRECTIVE
&& prop.name === 'bind'
&& prop.arg
&& prop.arg.type === NodeTypes.SIMPLE_EXPRESSION
&& prop.arg.isStatic
&& attrNames.includes(prop.arg.content.toLowerCase())
)
) {
props.splice(i, 1)
}
}
}
}
Loading
Loading