Skip to content
Open
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
198 changes: 198 additions & 0 deletions internal/testdrive/cypress.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2026 Datadog, Inc.

package testdrive

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/kballard/go-shellquote"
)

// prepareCypress wraps configuration inside the session; project config and
// support files are neither edited nor replaced on disk.
func prepareCypress(root, directory, preload, command string, args []string) ([]string, error) {
inspectionArgs := cypressInspectionArgs(root, command, args)
projectRoot := root
if project := optionValue(inspectionArgs, "--project", "-P"); project != "" {
if filepath.IsAbs(project) {
projectRoot = project
} else {
projectRoot = filepath.Join(root, project)
}
}
var config string
clean := make([]string, 0, len(args)+2)
for i := 0; i < len(args); i++ {
if args[i] == "--config-file" || args[i] == "-C" {
if i+1 == len(args) {
return nil, fmt.Errorf("--config-file requires a path")
}
i++
config = args[i]
continue
}
if strings.HasPrefix(args[i], "--config-file=") || strings.HasPrefix(args[i], "-C=") {
_, config, _ = strings.Cut(args[i], "=")
continue
}
clean = append(clean, args[i])
}
if config == "" {
config = optionValue(inspectionArgs, "--config-file", "-C")
}
if config == "false" {
config = ""
}
if config == "" {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Preserve config options from package scripts

When a package script selects a custom config, testdrive receives only npm test. The wrapper cannot see the config option and searches default names. The run then fails or loads the wrong config, so it loses customer hooks and settings.

Was this helpful? React 👍 or 👎
🤖 Bits Code Review · @DataDog review to ask questions · Open Bits AI session

for _, name := range []string{"cypress.config.ts", "cypress.config.js", "cypress.config.mjs", "cypress.config.cjs"} {
if _, err := os.Stat(filepath.Join(projectRoot, name)); err == nil {
config = name
break
}
}
}
if config != "" && !filepath.IsAbs(config) {
config = filepath.Join(projectRoot, config)
}
testingType := "e2e"
if optionPresent(inspectionArgs, "--component") {
testingType = "component"
}
tracerRoot := filepath.Dir(filepath.Dir(preload))
values, _ := json.Marshal(map[string]string{"root": projectRoot, "directory": directory, "tracer": tracerRoot, "testingType": testingType})
configImport := "const originalImport = {};\n"
if config != "" {
encodedConfig, _ := json.Marshal(config)
configImport = "import originalImport from " + string(encodedConfig) + ";\n"
}
encodedPlugin, _ := json.Marshal(filepath.Join(tracerRoot, "ci", "cypress", "plugin"))
wrapper := "import fs from 'node:fs';\nimport path from 'node:path';\n" + configImport +
"import instrumentImport from " + string(encodedPlugin) + ";\nconst options = " + string(values) + ";\n" + cypressWrapper
path := filepath.Join(directory, "cypress.config.ts")
if err := os.WriteFile(path, []byte(wrapper), 0600); err != nil {
return nil, err
}
return append(clean, "--config-file", path), nil
}

func optionValue(args []string, options ...string) string {
value := ""
for index := 0; index < len(args); index++ {
for _, option := range options {
if args[index] == option && index+1 < len(args) {
value = args[index+1]
index++
break
}
if candidate, found := strings.CutPrefix(args[index], option+"="); found {
value = candidate
break
}
}
}
return value
}

func optionPresent(args []string, option string) bool {
for _, arg := range args {
if arg == option || strings.HasPrefix(arg, option+"=") {
return true
}
}
return false
}

func cypressInspectionArgs(root, command string, args []string) []string {
for _, arg := range append([]string{command}, args...) {
if strings.Contains(strings.ToLower(filepath.Base(arg)), "cypress") {
return args
}
}
base := strings.ToLower(filepath.Base(command))
if base != "npm" && base != "yarn" && base != "pnpm" && base != "bun" {
return args
}
script := ""
if len(args) > 0 && args[0] == "test" {
script = "test"
} else if len(args) > 1 && (args[0] == "run" || args[0] == "run-script") {
script = args[1]
}
if script == "" {
return args
}
contents, err := os.ReadFile(filepath.Join(root, "package.json"))
if err != nil {
return args
}
var manifest struct {
Scripts map[string]string `json:"scripts"`
}
if json.Unmarshal(contents, &manifest) != nil {
return args
}
expanded, err := shellquote.Split(manifest.Scripts[script])
if err != nil {
return args
}
if separator := slicesIndex(args, "--"); separator >= 0 {
expanded = append(expanded, args[separator+1:]...)
}
return expanded
}

func slicesIndex(values []string, value string) int {
for index, candidate := range values {
if candidate == value {
return index
}
}
return -1
}

const cypressWrapper = `
// Cypress starts the config process in the wrapper's directory. Keep relative
// filesystem operations in the customer's config and hooks rooted in the project.
process.chdir(options.root);
export default (async () => {
const original = originalImport.default || originalImport;
const config = { ...original };
const types = new Set(['e2e', 'component'].filter(type => original[type]));
types.add(options.testingType);
for (const type of types) {
const originalType = original[type] || {};
const setup = originalType.setupNodeEvents;
config[type] = { ...originalType, async setupNodeEvents(on, resolved) {
// Compose hooks so adding instrumentation cannot discard customer hooks.
const handlers = new Map();
const collect = (event, handler) => {
if (event === 'task') { handlers.set(event, { ...(handlers.get(event) || {}), ...handler }); return; }
const previous = handlers.get(event);
handlers.set(event, previous ? async (...args) => {
const first = await previous(...args);
const second = await handler(...args);
return second === undefined ? first : second;
} : handler);
};
if (setup) resolved = { ...resolved, ...((await setup(collect, resolved)) || {}) };
const support = path.join(options.directory, type + '-support.cjs');
let contents = 'require(' + JSON.stringify(path.join(options.tracer, 'ci/cypress/support')) + ');\n';
if (resolved.supportFile) contents += 'require(' + JSON.stringify(path.resolve(resolved.projectRoot || options.root, resolved.supportFile)) + ');\n';
fs.writeFileSync(support, contents);
resolved.supportFile = support;
const instrument = instrumentImport.default || instrumentImport;
resolved = (await instrument(collect, resolved)) || resolved;
for (const [event, handler] of handlers) on(event, handler);
return resolved;
}};
}
return config;
})();
`
1 change: 1 addition & 0 deletions internal/testdrive/frameworks_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func TestPublicFrameworkTestdrives(t *testing.T) {
{"vitest", `{"type":"module","scripts":{"test":"vitest run"},"devDependencies":{"vitest":"3.2.4"}}`, "npm test", map[string]string{"one.test.js": `import {test,expect} from 'vitest'; test('adds', () => expect(1+1).toBe(2));`}},
{"playwright", `{"scripts":{"test":"playwright test"},"devDependencies":{"@playwright/test":"1.55.1"}}`, "npm test", map[string]string{"one.spec.js": `const {test,expect} = require('@playwright/test'); test('adds', () => expect(1+1).toBe(2));`}},
{"cucumber", `{"scripts":{"test":"cucumber-js"},"devDependencies":{"@cucumber/cucumber":"12.2.0"}}`, "npm test", map[string]string{"features/one.feature": "Feature: Arithmetic\n Scenario: Add\n Given addition works\n", "features/step_definitions/one.js": `const {Given} = require('@cucumber/cucumber'); Given('addition works', () => require('node:assert').equal(1+1,2));`}},
{"cypress", `{"scripts":{"test":"cypress run"},"devDependencies":{"cypress":"15.1.0"}}`, "npm test", map[string]string{"cypress.config.js": `module.exports={e2e:{supportFile:false,setupNodeEvents(on,config){on('task',{answer:()=>42});on('after:run',()=>{require('node:fs').writeFileSync('original-hook.txt','ran');});return config;}}};`, "cypress/e2e/one.cy.js": `it('preserves hooks', () => { cy.task('answer').should('equal',42); });`}},
}
for _, fixture := range fixtures {
t.Run(fixture.name, func(t *testing.T) {
Expand Down
49 changes: 48 additions & 1 deletion internal/testdrive/multiframework_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
)

func TestPrepareAllSupportedFrameworks(t *testing.T) {
for _, name := range []string{"jest", "mocha", "vitest", "playwright", "cucumber"} {
for _, name := range []string{"jest", "mocha", "vitest", "playwright", "cucumber", "cypress"} {
t.Run(name, func(t *testing.T) {
root := t.TempDir()
switch name {
Expand Down Expand Up @@ -116,3 +116,50 @@ func TestPrepareRequiresSelectionForMultipleFrameworks(t *testing.T) {
_, err = Prepare("latest")
require.ErrorContains(t, err, "unsupported framework")
}

func TestCypressWrapperUsesExplicitConfigWithoutEditingIt(t *testing.T) {
root := t.TempDir()
session := t.TempDir()
config := `module.exports={e2e:{supportFile:false}}`
requireWriteFile(t, filepath.Join(root, "custom.cjs"), config)
args, err := prepareCypress(root, session, "/tracer/ci/init.js", "cypress", []string{"run", "--config-file=custom.cjs", "--browser", "chrome"})
require.NoError(t, err)
require.Equal(t, []string{"run", "--browser", "chrome", "--config-file", filepath.Join(session, "cypress.config.ts")}, args)
contents, err := os.ReadFile(filepath.Join(root, "custom.cjs"))
require.NoError(t, err)
require.Equal(t, config, string(contents))
wrapper, err := os.ReadFile(filepath.Join(session, "cypress.config.ts"))
require.NoError(t, err)
require.Contains(t, string(wrapper), filepath.Join(root, "custom.cjs"))
_, err = prepareCypress(root, session, "/tracer/ci/init.js", "cypress", []string{"--config-file"})
require.ErrorContains(t, err, "requires a path")
}

func TestCypressWrapperReadsPackageScriptProjectAndConfig(t *testing.T) {
root := t.TempDir()
session := t.TempDir()
project := filepath.Join(root, "apps", "web")
require.NoError(t, os.MkdirAll(project, 0755))
requireWriteFile(t, filepath.Join(root, "package.json"), `{"scripts":{"test":"cypress run --project apps/web -C custom.ts"}}`)
requireWriteFile(t, filepath.Join(project, "custom.ts"), `export default {}`)

args, err := prepareCypress(root, session, "/tracer/ci/init.js", "npm", []string{"test", "--"})
require.NoError(t, err)
require.Equal(t, []string{"test", "--", "--config-file", filepath.Join(session, "cypress.config.ts")}, args)
wrapper, err := os.ReadFile(filepath.Join(session, "cypress.config.ts"))
require.NoError(t, err)
require.Contains(t, string(wrapper), filepath.Join(project, "custom.ts"))
require.Contains(t, string(wrapper), `"root":"`+project+`"`)
}

func TestCypressWrapperSupportsConfigFileFalseAndDefaultE2E(t *testing.T) {
root := t.TempDir()
session := t.TempDir()
args, err := prepareCypress(root, session, "/tracer/ci/init.js", "cypress", []string{"run", "-C", "false"})
require.NoError(t, err)
require.Equal(t, []string{"run", "--config-file", filepath.Join(session, "cypress.config.ts")}, args)
wrapper, err := os.ReadFile(filepath.Join(session, "cypress.config.ts"))
require.NoError(t, err)
require.Contains(t, string(wrapper), `types.add(options.testingType)`)
require.Contains(t, string(wrapper), `const originalImport = {}`)
}
15 changes: 14 additions & 1 deletion internal/testdrive/testdrive.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"maps"
"os"
"path/filepath"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -79,7 +80,7 @@ func Prepare(version string) (*Testdrive, error) {
}
language := detectedPlatform.Name()
switch runner.Name() {
case "jest", "mocha", "vitest", "playwright", "cucumber":
case "jest", "mocha", "vitest", "playwright", "cucumber", "cypress":
default:
return nil, fmt.Errorf("testdrive does not yet support %s", runner.Name())
}
Expand Down Expand Up @@ -134,6 +135,9 @@ func (t *Testdrive) Preview(output io.Writer) {
_, _ = fmt.Fprintf(output, " - install %s: %s\n", t.tracerLabel, shellquote.Join(install...))
}

if t.framework.Name() == "cypress" {
_, _ = fmt.Fprintf(output, " - create Cypress config/support wrappers in %s and preserve existing hooks\n", directory)
}
_, _ = fmt.Fprintf(output, " - run: %s\n", shellquote.Join(append([]string{command}, args...)...))
_, _ = fmt.Fprintln(output)
patterns := map[string][]string{
Expand Down Expand Up @@ -204,6 +208,15 @@ func (t *Testdrive) Run(ctx context.Context, output io.Writer) (runErr error) {
_, _ = fmt.Fprintf(output, "Running %s...\n", shellquote.Join(append([]string{command}, args...)...))
env := t.environment(installation.Path, server.URL(), session.ID())
maps.Copy(env, installation.Env)
if t.framework.Name() == "cypress" {
if command == "npm" && !slices.Contains(args, "--") {
args = append(slices.Clone(args), "--")
}
args, err = prepareCypress(t.repositoryRoot, session.Directory(), installation.Path, command, args)
if err != nil {
return err
}
}

testOutput, testErr := t.executor.CombinedOutput(ctx, command, args, env)

Expand Down
Loading