Skip to content

Commit

Permalink
refactor: use aliases instead of meta (#19566)
Browse files Browse the repository at this point in the history
* refactor: use aliases instead of meta

+ use fs/promise instead of promisify

* refactor: move function "start" from resolveConfig

* fix: finish refactor

* refactor: better name for hasSupportPath file

* test: add project vite-ct

* test: add system test for vite

* test: update test name
  • Loading branch information
elevatebart authored Jan 19, 2022
1 parent 5035155 commit 5cdf2ee
Show file tree
Hide file tree
Showing 13 changed files with 1,604 additions and 56 deletions.
13 changes: 7 additions & 6 deletions npm/vite-dev-server/client/initCypressTests.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// This file is merged in a <script type=module> into index.html
// it will be used to load and kick start the selected spec

const supportPath = import.meta.env.__cypress_supportPath
const originAutUrl = import.meta.env.__cypress_originAutUrl
import specLoaders from 'cypress:spec-loaders'
import { hasSupportPath, originAutUrl } from 'cypress:config'

const specPath = window.location.pathname.replace(originAutUrl, '')

const importsToLoad = [() => import(/* @vite-ignore */ specPath)]
const specLoader = specLoaders[specPath]
const importsToLoad = [specLoader || (() => import(/* @vite-ignore */ specPath))]

if (supportPath) {
importsToLoad.unshift(() => import(/* @vite-ignore */ supportPath))
if (hasSupportPath) {
importsToLoad.unshift(() => import('cypress:support-path'))
}

const CypressInstance = window.Cypress = parent.Cypress
Expand Down Expand Up @@ -46,3 +46,4 @@ CypressInstance.on('test:before:run', () => {

// Make usage of node test plugins possible
window.global = window
window.process = typeof process !== 'undefined' ? process : {}
20 changes: 14 additions & 6 deletions npm/vite-dev-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import { debug as debugFn } from 'debug'
import { InlineConfig } from 'vite'
import { start as createDevServer, StartDevServerOptions } from './startServer'
import { createServer, InlineConfig } from 'vite'
import { resolveServerConfig, StartDevServerOptions } from './resolveServerConfig'
const debug = debugFn('cypress:vite-dev-server:vite')

export { StartDevServerOptions }

export async function startDevServer (startDevServerArgs: StartDevServerOptions): Promise<Cypress.ResolvedDevServerConfig> {
const viteDevServer = await createDevServer(startDevServerArgs)
if (!startDevServerArgs.viteConfig) {
debug('User did not pass in any Vite dev server configuration')
startDevServerArgs.viteConfig = {}
}

const app = await viteDevServer.listen()
const port = app.config.server.port!
debug('starting vite dev server')
const resolvedConfig = await resolveServerConfig(startDevServerArgs)
const port = resolvedConfig.server!.port!

const viteDevServer = await createServer(resolvedConfig)

await viteDevServer.listen()

debug('Component testing vite server started on port', port)

return { port, close: app.httpServer!.close }
return { port, close: viteDevServer.close }
}

export type CypressViteDevServerConfig = Omit<InlineConfig, 'base' | 'root'>
Expand Down
75 changes: 44 additions & 31 deletions npm/vite-dev-server/src/makeCypressPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { resolve, sep } from 'path'
import { readFile } from 'fs'
import { promisify } from 'util'
import { readFile } from 'fs/promises'
import Debug from 'debug'
import { ModuleNode, Plugin, ViteDevServer } from 'vite'
import { ModuleNode, normalizePath, Plugin, ViteDevServer } from 'vite'

const debug = Debug('cypress:vite-dev-server:plugin')

const read = promisify(readFile)

const pluginName = 'cypress-transform-html'
const OSSepRE = new RegExp(`\\${sep}`, 'g')

Expand Down Expand Up @@ -48,40 +45,56 @@ export const makeCypressPlugin = (

const posixSupportFilePath = supportFilePath ? convertPathToPosix(resolve(projectRoot, supportFilePath)) : undefined

const normalizedSupportFilePath = posixSupportFilePath ? `${base}@fs/${posixSupportFilePath}` : undefined

return {
name: pluginName,
enforce: 'pre',
config (_, env) {
if (env) {
return {
define: {
'import.meta.env.__cypress_supportPath': JSON.stringify(normalizedSupportFilePath),
'import.meta.env.__cypress_originAutUrl': JSON.stringify(`__cypress/iframes/${convertPathToPosix(projectRoot)}/`),
},
}
}
},
configResolved (config) {
base = config.base
},
transformIndexHtml () {
debug('transformIndexHtml with base', base)

return [
// load the script at the end of the body
// script has to be loaded when the vite client is connected
{
tag: 'script',
injectTo: 'body',
attrs: { type: 'module' },
children: `import(${JSON.stringify(`${base}@fs/${INIT_FILEPATH}`)})`,
},
]
async transformIndexHtml () {
const indexHtmlPath = resolve(__dirname, '..', 'index.html')
const indexHtmlContent = await readFile(indexHtmlPath, { encoding: 'utf8' })
// find </body> last index
const endOfBody = indexHtmlContent.lastIndexOf('</body>')

// insert the script in the end of the body
return `${indexHtmlContent.substring(0, endOfBody)
}<script src="${base}cypress:client-init-test" type="module"></script>${
indexHtmlContent.substring(endOfBody)
}`
},
resolveId (id) {
if (id === 'cypress:config') {
return id
}

if (id === 'cypress:support-path') {
return posixSupportFilePath
}

if (id === 'cypress:spec-loaders') {
return id
}

if (id === '/cypress:client-init-test') {
return INIT_FILEPATH
}
},
load (id) {
if (id === 'cypress:spec-loaders') {
return `export default {\n${specs.map((s) => {
return `${JSON.stringify(s.relative)}:()=>import(${JSON.stringify(s.absolute)})`
}).join(',\n')}\n}`
}

if (id === 'cypress:config') {
return `
export const hasSupportPath = ${JSON.stringify(!!supportFilePath)}
export const originAutUrl = ${JSON.stringify(`/__cypress/iframes/${normalizePath(projectRoot)}/`)}`
}
},
configureServer: async (server: ViteDevServer) => {
const indexHtml = await read(resolve(__dirname, '..', 'index.html'), { encoding: 'utf8' })
const indexHtml = await readFile(resolve(__dirname, '..', 'index.html'), { encoding: 'utf8' })

const transformedIndexHtml = await server.transformIndexHtml(base, indexHtml)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface StartDevServerOptions {
viteConfig?: Omit<InlineConfig, 'base' | 'root'>
}

const resolveServerConfig = async ({ viteConfig, options }: StartDevServerOptions): Promise<InlineConfig> => {
export const resolveServerConfig = async ({ viteConfig, options }: StartDevServerOptions): Promise<InlineConfig> => {
const { projectRoot, supportFile } = options.config

const requiredOptions: InlineConfig = {
Expand Down Expand Up @@ -74,15 +74,3 @@ const resolveServerConfig = async ({ viteConfig, options }: StartDevServerOption

return finalConfig
}

export async function start (devServerOptions: StartDevServerOptions): Promise<ViteDevServer> {
if (!devServerOptions.viteConfig) {
debug('User did not pass in any Vite dev server configuration')
devServerOptions.viteConfig = {}
}

debug('starting vite dev server')
const resolvedConfig = await resolveServerConfig(devServerOptions)

return createServer(resolvedConfig)
}
3 changes: 3 additions & 0 deletions system-tests/projects/vite-ct/cypress.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"retries": null
}
14 changes: 14 additions & 0 deletions system-tests/projects/vite-ct/cypress/component/support.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
describe('Support files', () => {
it('can load a support file', () => {
const $body = Cypress.$('body')

// Visual cue to help debug
const $supportNode = Cypress.$(`<h1>Support file hasn't been loaded 😿</h1>`)

$body.append($supportNode)

// @ts-ignore
expect(window.supportFileWasLoaded).to.be.true
$supportNode.text('Support file was loaded! ⚡️')
})
})
9 changes: 9 additions & 0 deletions system-tests/projects/vite-ct/cypress/plugins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { startDevServer } = require('@cypress/vite-dev-server')

module.exports = (on) => {
on('dev-server:start', async (options) => {
return startDevServer({
options,
})
})
}
3 changes: 3 additions & 0 deletions system-tests/projects/vite-ct/cypress/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body{
color:aquamarine
}
6 changes: 6 additions & 0 deletions system-tests/projects/vite-ct/cypress/support.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import '@testing-library/cypress/add-commands'
import './styles.css'

before(() => {
window.supportFileWasLoaded = true
})
12 changes: 12 additions & 0 deletions system-tests/projects/vite-ct/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@test-project/vite-ct",
"version": "0.0.0-test",
"private": true,
"dependencies": {
"@cypress/vite-dev-server": "file:../../../npm/vite-dev-server",
"@testing-library/cypress": "8.0.2",
"cypress": "file:../../../cli/build",
"typescript": "4.2.3",
"vite": "2.7.10"
}
}
21 changes: 21 additions & 0 deletions system-tests/projects/vite-ct/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"baseUrl": "./",
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"isolatedModules": true,
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"],
"skipLibCheck": true
},
"include": ["vite.config.*", "env.d.ts", "src/**/*", "cypress/**/*"]
}
Loading

0 comments on commit 5cdf2ee

Please sign in to comment.