Skip to content

Commit

Permalink
fix: scaffold correct config file (#19776)
Browse files Browse the repository at this point in the history
* fix: scaffold correct config file

* update setConfigFilePath

* Update test

* Update with code review

* remove default supportFile

* Update supportFile default value

* Add test

* Fix identation

* Update with feedback

* fix english pluralization

Co-authored-by: Tim Griesser <tgriesser10@gmail.com>
  • Loading branch information
estrada9166 and tgriesser committed Jan 24, 2022
1 parent d307abe commit 8f32960
Show file tree
Hide file tree
Showing 26 changed files with 106 additions and 51 deletions.
2 changes: 1 addition & 1 deletion cli/schema/cypress.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@
"string",
"boolean"
],
"default": "cypress/support/e2e.js",
"default": "cypress/support/e2e.{js,jsx,ts,tsx}",
"description": "Path to file to load before test files load. This file is compiled and bundled. (Pass false to disable)"
},
"videosFolder": {
Expand Down
1 change: 0 additions & 1 deletion npm/angular/cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export default defineConfig({
'fileServerFolder': 'src',
'projectId': 'nf7zag',
'component': {
'supportFile': 'cypress/support/component.ts',
setupNodeEvents (on, config) {
return require('./cypress/plugins')(on, config)
},
Expand Down
1 change: 0 additions & 1 deletion npm/react/examples/find-webpack/cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ export default defineConfig({
'video': true,
'projectId': 'jq5xpp',
'component': {
'supportFile': 'cypress/support/component.ts',
devServer (cypressConfig) {
const findReactScriptsWebpackConfig = require('@cypress/react/plugins/react-scripts/findReactScriptsWebpackConfig')
const { startDevServer } = require('@cypress/webpack-dev-server')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ module.exports = defineConfig({
'viewportWidth': 500,
'viewportHeight': 800,
'component': {
'supportFile': 'cypress/support/component.ts',
devServer: require('@cypress/react/plugins/react-scripts'),
},
})
2 changes: 1 addition & 1 deletion packages/config/__snapshots__/index_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ exports['src/index .getDefaultValues returns list of public config keys 1'] = {
"screenshotsFolder": "cypress/screenshots",
"slowTestThreshold": 10000,
"scrollBehavior": "top",
"supportFile": "cypress/support/e2e.js",
"supportFile": "cypress/support/e2e.{js,jsx,ts,tsx}",
"supportFolder": false,
"taskTimeout": 60000,
"trashAssetsBeforeRuns": true,
Expand Down
2 changes: 1 addition & 1 deletion packages/config/lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ const resolvedOptions: Array<ResolvedConfigOption> = [
canUpdateDuringTestTime: true,
}, {
name: 'supportFile',
defaultValue: (options: Record<string, any> = {}) => options.testingType === 'component' ? 'cypress/support/component.js' : 'cypress/support/e2e.js',
defaultValue: (options: Record<string, any> = {}) => options.testingType === 'component' ? 'cypress/support/component.{js,jsx,ts,tsx}' : 'cypress/support/e2e.{js,jsx,ts,tsx}',
validation: validate.isStringOrFalse,
isFolder: true,
canUpdateDuringTestTime: false,
Expand Down
34 changes: 10 additions & 24 deletions packages/data-context/src/actions/WizardActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import fs from 'fs'
import path from 'path'

import type { DataContext } from '..'
import { getDefaultSpecPatterns } from '../util/config-options'

interface WizardGetCodeComponent {
chosenLanguage: CodeLanguage
Expand Down Expand Up @@ -144,6 +143,7 @@ export class WizardActions {
}

private async scaffoldConfig (configCode: string): Promise<NexusGenObjects['ScaffoldedFile']> {
this.ctx.lifecycleManager.setConfigFilePath(this.ctx.coreData.wizard.chosenLanguage)
if (!fs.existsSync(this.ctx.lifecycleManager.configFilePath)) {
return this.scaffoldFile(
this.ctx.lifecycleManager.configFilePath,
Expand Down Expand Up @@ -196,9 +196,7 @@ export class WizardActions {
codeBlocks.push(lang === 'ts' ? `import { defineConfig } from 'cypress'` : `const { defineConfig } = require('cypress')`)
codeBlocks.push('')
codeBlocks.push(lang === 'ts' ? `export default defineConfig({` : `module.exports = defineConfig({`)
codeBlocks.push(` ${E2E_SCAFFOLD_BODY({
lang,
}).replace(/\n/g, '\n ')}`)
codeBlocks.push(` ${E2E_SCAFFOLD_BODY.replace(/\n/g, '\n ')}`)

codeBlocks.push('})\n')

Expand All @@ -212,7 +210,7 @@ export class WizardActions {
codeBlocks.push(chosenLanguage.type === 'ts' ? `import { defineConfig } from 'cypress'` : `const { defineConfig } = require('cypress')`)
codeBlocks.push('')
codeBlocks.push(chosenLanguage.type === 'ts' ? `export default defineConfig({` : `module.exports = defineConfig({`)
codeBlocks.push(`// Component testing, ${chosenLanguage.name}, ${chosenFramework.name}, ${chosenBundler.name}`)
codeBlocks.push(` // Component testing, ${chosenLanguage.name}, ${chosenFramework.name}, ${chosenBundler.name}`)

codeBlocks.push(` ${COMPONENT_SCAFFOLD_BODY({
lang: chosenLanguage.type,
Expand Down Expand Up @@ -319,23 +317,13 @@ export class WizardActions {
}
}

interface E2eScaffoldOpts {
lang: CodeLanguageEnum
}

const E2E_SCAFFOLD_BODY = (opts: E2eScaffoldOpts) => {
return dedent`
const E2E_SCAFFOLD_BODY = dedent`
e2e: {
supportFile: 'cypress/support/e2e.${opts.lang}',
specPattern: '${getDefaultSpecPatterns().e2e}',
viewportHeight: 660,
viewportWidth: 1000,
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
`
}
`

interface ComponentScaffoldOpts {
lang: CodeLanguageEnum
Expand All @@ -346,13 +334,11 @@ interface ComponentScaffoldOpts {

const COMPONENT_SCAFFOLD_BODY = (opts: ComponentScaffoldOpts) => {
return dedent`
component: {
supportFile: 'cypress/support/component.${opts.lang}',
specPattern: '${getDefaultSpecPatterns().component}',
devServer: import('${opts.requirePath}'),
devServerConfig: ${opts.configOptionsString}
},
`
component: {
devServer: import('${opts.requirePath}'),
devServerConfig: ${opts.configOptionsString}
},
`
}

const FIXTURE_DATA = {
Expand Down
10 changes: 7 additions & 3 deletions packages/data-context/src/data/ProjectLifecycleManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1105,20 +1105,20 @@ export class ProjectLifecycleManager {

if (fs.existsSync(configFileTs)) {
metaState.hasValidConfigFile = true
this._configFilePath = configFileTs
this.setConfigFilePath('ts')
}

if (fs.existsSync(configFileJs)) {
metaState.hasValidConfigFile = true
if (this._configFilePath) {
metaState.hasMultipleConfigPaths = true
} else {
this._configFilePath = configFileJs
this.setConfigFilePath('js')
}
}

if (!this._configFilePath) {
this._configFilePath = metaState.hasTypescript ? configFileTs : configFileJs
this.setConfigFilePath(metaState.hasTypescript ? 'ts' : 'js')
}

if (metaState.hasLegacyCypressJson && !metaState.hasValidConfigFile) {
Expand All @@ -1130,6 +1130,10 @@ export class ProjectLifecycleManager {
return metaState
}

setConfigFilePath (lang: 'ts' | 'js') {
this._configFilePath = this._pathToFile(`cypress.config.${lang}`)
}

private _pathToFile (file: string) {
return path.isAbsolute(file) ? file : path.join(this.projectRoot, file)
}
Expand Down
1 change: 0 additions & 1 deletion packages/frontend-shared/cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export default defineConfig({
'configFile': '../../mocha-reporter-config.json',
},
'component': {
'supportFile': 'cypress/support/component.ts',
devServer (cypressConfig, devServerConfig) {
const { startDevServer } = require('@cypress/vite-dev-server')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export const e2eProjectDirs = [
'max-listeners',
'migration',
'multiple-task-registrations',
'multiples-config-files-with-json',
'multiple-config-files-with-json',
'multiple-support-files',
'no-scaffolding',
'no-server',
'no-specs-found',
Expand Down
30 changes: 27 additions & 3 deletions packages/launchpad/cypress/e2e/onboarding-flow.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,39 @@ describe('Launchpad: Onboarding Flow', () => {
cy.findByText('I\'ve installed them').click()
cy.findByText('We added the following files to your project.')
cy.findByText('Continue').click()
cy.withCtx(async (ctx) => {
cy.withCtx((ctx) => {
return ctx.file.readFileInProject('cypress.config.js')
}).then((str) => {
cy.log(str)
})

cy.findByText('Choose a Browser', { timeout: 10000 })
})

it('can setup component testing with TS', () => {
cy.visitLaunchpad()
cy.get('[data-cy-testingType=component]').click()
cy.get('[data-testid=select-framework]').click()
cy.findByText('React.js').click()
cy.get('[data-testid=select-framework]').should('contain', 'React.js')
cy.get('[data-testid=select-bundler]')
.findByText(cy.i18n.setupPage.projectSetup.bundlerPlaceholder)
.click()

cy.findByText('Webpack').click()
cy.get('[data-testid=select-bundler]').should('contain', 'Webpack')
cy.reload()
cy.get('[data-testid=select-framework]').should('contain', 'React.js')
cy.get('[data-testid=select-bundler]').should('contain', 'Webpack')
cy.findByText('TypeScript').click()
cy.findByText('Next Step').click()
cy.get('h1').should('contain', 'Dependencies')
cy.findByText('I\'ve installed them').click()
cy.findByText('We added the following files to your project.')
cy.findByText('Continue').click()
cy.withCtx((ctx) => {
return ctx.file.readFileInProject('cypress.config.ts')
})
})

it('can setup e2e testing', () => {
cy.visitLaunchpad()
cy.get('[data-cy-testingType=e2e]').click()
Expand Down
1 change: 0 additions & 1 deletion packages/reporter/cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export default defineConfig({
'openMode': 0,
},
'e2e': {
'supportFile': 'cypress/support/e2e.ts',
setupNodeEvents (on, config) {
const express = require('express')

Expand Down
18 changes: 16 additions & 2 deletions packages/server/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,15 +348,29 @@ export const setNodeBinary = (obj, userNodePath, userNodeVersion) => {
}

// async function
export function setSupportFileAndFolder (obj, defaults) {
export async function setSupportFileAndFolder (obj, defaults) {
if (!obj.supportFile) {
return Bluebird.resolve(obj)
}

obj = _.clone(obj)

const ctx = getCtx()

const supportFilesByGlob = await ctx.file.getFilesByGlob(obj.projectRoot, obj.supportFile, { absolute: false })

if (supportFilesByGlob.length > 1) {
return errors.throw('MULTIPLE_SUPPORT_FILES_FOUND', obj.supportFile, supportFilesByGlob.join(', '))
}

if (supportFilesByGlob.length === 0) {
const configFile = obj.configFile || defaults.configFile

return errors.throw('SUPPORT_FILE_NOT_FOUND', path.resolve(obj.projectRoot, obj.supportFile), configFile)
}

// TODO move this logic to find support file into util/path_helpers
const sf = obj.supportFile
const sf = supportFilesByGlob[0]

debug(`setting support file ${sf}`)
debug(`for project root ${obj.projectRoot}`)
Expand Down
9 changes: 9 additions & 0 deletions packages/server/lib/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,15 @@ const getMsgByType = function (type, ...args) {
https://on.cypress.io/renderer-process-crashed`
case 'AUTOMATION_SERVER_DISCONNECTED':
return 'The automation client disconnected. Cannot continue running tests.'

case 'MULTIPLE_SUPPORT_FILES_FOUND':
return stripIndent`\
There are multiple support files.
Your \`supportFile\` is set to \`${arg1}\`, and we found \`${arg2}\`.
Correct your supportFile config or merge the files into one.`

case 'SUPPORT_FILE_NOT_FOUND':
return stripIndent`\
The support file is missing or invalid.
Expand Down
1 change: 0 additions & 1 deletion packages/server/test/unit/config_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1997,7 +1997,6 @@ describe('lib/config', () => {

context('.setSupportFileAndFolder', () => {
const mockSupportDefaults = {
supportFile: 'cypress/support/e2e.ts',
supportFolder: false,
configFile: 'cypress.json',
}
Expand Down
2 changes: 1 addition & 1 deletion system-tests/__snapshots__/config_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ Cypress no longer supports 'cypress.json', please migrate to 'cypress.config.{ts

exports['e2e config throws error when cypress.json is found in project and cypress.config.{ts|js} exists as well 1'] = `
There is both a \`cypress.config.js\` and a cypress.json file at the location below:
/foo/bar/.projects/multiples-config-files-with-json
/foo/bar/.projects/multiple-config-files-with-json
Cypress no longer supports 'cypress.json' config, please remove it from your project.
Expand Down
8 changes: 8 additions & 0 deletions system-tests/__snapshots__/multiple_support_files_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
exports['e2e multiple support files passes 1'] = `
There are multiple support files.
Your \`supportFile\` is set to \`/foo/bar/.projects/multiple-support-files/cypress/support/e2e.{js,jsx,ts,tsx}\`, and we found \`/foo/bar/.projects/multiple-support-files/cypress/support/e2e.js, /foo/bar/.projects/multiple-support-files/cypress/support/e2e.ts\`.
Correct your supportFile config or merge the files into one.
`
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
it('is true', () => {
expect(true).to.be.true
})
Empty file.
Empty file.
6 changes: 1 addition & 5 deletions system-tests/projects/ts-proj/cypress.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
module.exports = {
'e2e': {
'supportFile': 'cypress/support/e2e.ts',
},
}
module.exports = {}
6 changes: 3 additions & 3 deletions system-tests/test/config_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ describe('e2e config', () => {
})

it('throws error when cypress.json is found in project and cypress.config.{ts|js} exists as well', function () {
Fixtures.scaffoldProject('multiples-config-files-with-json')
Fixtures.projectPath('multiples-config-files-with-json')
Fixtures.scaffoldProject('multiple-config-files-with-json')
Fixtures.projectPath('multiple-config-files-with-json')

return systemTests.exec(this, {
project: 'multiples-config-files-with-json',
project: 'multiple-config-files-with-json',
expectedExitCode: 1,
snapshot: true,
})
Expand Down
15 changes: 15 additions & 0 deletions system-tests/test/multiple_support_files_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const systemTests = require('../lib/system-tests').default

describe('e2e multiple support files', () => {
systemTests.setup()

it('passes', function () {
return systemTests.exec(this, {
project: 'multiple-support-files',
sanitizeScreenshotDimensions: true,
snapshot: true,
expectedExitCode: 1,
onStdout: systemTests.normalizeWebpackErrors,
})
})
})

3 comments on commit 8f32960

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 8f32960 Jan 24, 2022

Choose a reason for hiding this comment

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

Circle has built the linux x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/10.0.0/circle-10.0-release-8f32960ef803f539f065d41f01fff33bfe33ed5d/cypress.tgz

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 8f32960 Jan 24, 2022

Choose a reason for hiding this comment

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

Circle has built the win32 x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/10.0.0/circle-10.0-release-8f32960ef803f539f065d41f01fff33bfe33ed5d/cypress.tgz

@cypress-bot
Copy link
Contributor

@cypress-bot cypress-bot bot commented on 8f32960 Jan 24, 2022

Choose a reason for hiding this comment

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

Circle has built the darwin x64 version of the Test Runner.

Learn more about this pre-release platform-specific build at https://on.cypress.io/installing-cypress#Install-pre-release-version.

Run this command to install the pre-release locally:

npm install https://cdn.cypress.io/beta/npm/10.0.0/circle-10.0-release-8f32960ef803f539f065d41f01fff33bfe33ed5d/cypress.tgz

Please sign in to comment.