cypress component test with rollup bundler

74 Views Asked by At

The primary bundler in my mono-repo is rollup . I am trying to configure cypress component test following the documentation here . My cypress.config.ts file is below

const INIT_FILEPATH = path.resolve(__dirname, './initCypress.js')

async function startDevServer(cypressConfig: Cypress.PluginConfigOptions) {
    const { indexHtmlFile } = cypressConfig

    const loader = fs.readFileSync(INIT_FILEPATH, 'utf8')

    const server = express()
    server.use(express.static('__cypress'))
    server.use(express.static('cypress/support/component.ts'))

    server.get(
        `${cypressConfig.devServerPublicPathRoute}/index.html`,
        async (_req, res) => {
            // read custom index.html file
            const html = await fs.promises.readFile(
                path.join(
                    cypressConfig.projectRoot,
                    cypressConfig.indexHtmlFile,
                ),
                { encoding: 'utf8' },
            )

            const root = parse(html)

            const scriptTagsToInject = root.childNodes.filter(
                node =>
                    node instanceof HTMLElement && node.rawTagName === 'script',
            )

            const indexHtmlPath = path.resolve(projectRoot, indexHtmlFile)

            let indexHtmlContent = await fs.promises.readFile(indexHtmlPath, {
                encoding: 'utf8',
            })

            // Inject the script tags
            indexHtmlContent = indexHtmlContent.replace(
                '<head>',
                `<head>
                ${scriptTagsToInject.join('')}
                `,
            )

            // find </body> last index
            const endOfBody = indexHtmlContent.lastIndexOf('</body>')

            // insert the script in the end of the body
            const newHtml = `
        ${indexHtmlContent.substring(0, endOfBody)}
        <script>${loader}</script>
        ${indexHtmlContent.substring(endOfBody)}
      `
            res.end(newHtml)
        },
    )

    const { projectRoot } = cypressConfig
    const supportFilePath = cypressConfig.supportFile
        ? cypressConfig.supportFile.replace(projectRoot, '')
        : false

    // load support file
    server.get(
        `${cypressConfig.devServerPublicPathRoute}${supportFilePath}`,
        (_req, res) => {
            res.sendFile(path.resolve(cypressConfig.supportFile.toString()))
        },
    )

    // load spec files dynamically
    server.get(/.*\.cy.(js|jsx|ts|tsx)$/, (req, res) => {
        const specFile = req.url?.replace(
            cypressConfig.devServerPublicPathRoute,
            '',
        )
        res.sendFile(path.resolve(specFile))
    })

    server.use(
        cypressConfig.devServerPublicPathRoute,
        express.static('./cypress'),
    )

    const app = server.listen(3000)

    return {
        port: 3000,
        close: () => app.close(err => process.exit(err ? 1 : 0)),
        name: 'cypress:main',
        root: projectRoot,
        base: `${cypressConfig.devServerPublicPathRoute}`,
    }
}

export default defineConfig({
    component: {
        async devServer({ cypressConfig }) {
            const { port, close, base, root } = await startDevServer(
                cypressConfig,
            )

            return {
                port,
                close,
                base,
                root,
            }
        },
        indexHtmlFile: './cypress/support/component-index.html',
        specPattern: 'src/**/*.cy.{js,jsx,ts,tsx}',
        supportFolder: './cypress/support',
    },
})

My initCypress.js is exactly as written here and explained in the documentation here.

The problem is both my support file cypress/support/component.ts and spec files don't get compiled or bundled by my rollup or typescript compiler as such, my cypress test throws the error below . notice the component.ts and the DataLabelCustmisation.cy.jsx files. When I changed the component.ts to component.js, I got a different error at import { mount } from 'cypress/react18' . This is understandable because cypress dependency was not bundled along with the component.ts . My question is , Do I have to bundle each file/spec with it dependencies individually ? What is the right way to handle the bundles in this case with rollup ? Any help will be appreciated.

cypress

0

There are 0 best solutions below