Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ChunkLoadError > Loading chunk cypress-support-file failed #28644

Open
bene-starzengruber opened this issue Jan 5, 2024 · 122 comments
Open

ChunkLoadError > Loading chunk cypress-support-file failed #28644

bene-starzengruber opened this issue Jan 5, 2024 · 122 comments
Assignees
Labels
CT Issue related to component testing Cypress 14 Issues scoped for Cypress 14 experimental: just-in-time-compile stage: awaiting response Potential fix was proposed; awaiting response

Comments

@bene-starzengruber
Copy link

Current behavior

After updating from [email protected] to [email protected], we are seeing this error occasionally on our CI runs.

ChunkLoadError: The following error originated from your test code, not from Cypress.
> Loading chunk cypress-support-file failed.
[(error: http://localhost:8080/__cypress/src/cypress-support-file.js)]
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
[at __webpack_require__.f.j (http://localhost:8080/__cypress/src/runtime.js:272:29)]
[at <unknown> (http://localhost:8080/__cypress/src/runtime.js:126:40)]
at Array.reduce (<anonymous>)
[at __webpack_require__.e (http://localhost:8080/__cypress/src/runtime.js:125:67)]
[at Object.load (http://localhost:8080/__cypress/src/cypress-entry.js:33:192)]
[at <unknown> (http://localhost:8080/__cypress/runner/cypress_runner.js:110819:21)]
[at tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23)]
[at Object.gotValue (http://localhost:8080/__cypress/runner/cypress_runner.js:6476:18)]
[at Object.gotAccum (http://localhost:8080/__cypress/runner/cypress_runner.js:6465:25)]
[at Object.tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23)]

Unfortunately it is not reproducable locally, so I can not give you a repository to check.
I know that this might make it hard to investigate but maybe somebody already fell over the same issue or others are experiencing it as well.

The test fails around 30% of the time.

Desired behavior

No response

Test code to reproduce

no reproduction repository

Cypress Version

13.6.2

Node version

18.19.0

Operating System

Ubuntu 22.04.3

Debug Logs

No response

Other

No response

@jennifer-shehane
Copy link
Member

We made an update from webpack 4 to webpack 5 in 12.17.4, I wonder if it has anything to do with that upgrade. https://docs.cypress.io/guides/references/changelog#12-17-4

@jennifer-shehane jennifer-shehane added the stage: needs information Not enough info to reproduce the issue label Jan 5, 2024
@cubanx
Copy link

cubanx commented Jan 5, 2024

We are getting the same error also intermittently. I don't think we had it as far back as 12.17.4 but I can't say that for certain.

It only seems to happen toward the end of our Component Test runs. We have 1500+ component tests that we are running.

The following error originated from your test code, not from Cypress.

  > Loading chunk cypress-support-file failed.
(error: http://localhost:8080/__cypress/src/cypress-support-file.js)

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
ChunkLoadError: The following error originated from your test code, not from Cypress.
  > Loading chunk cypress-support-file failed.
(error: http://localhost:8080/__cypress/src/cypress-support-file.js
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
    at __webpack_require__.f.j (http://localhost:8080/__cypress/src/main.js:8702:29
    at <unknown> (http://localhost:8080/__cypress/src/main.js:8552:40
    at Array.reduce (<anonymous>)
    at __webpack_require__.e (http://localhost:8080/__cypress/src/main.js:8551:67
    at Object.load (http://localhost:8080/__cypress/src/main.js:1510:582
    at <unknown> (http://localhost:8080/__cypress/runner/cypress_runner.js:110819:21
    at tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23
    at Object.gotValue (http://localhost:8080/__cypress/runner/cypress_runner.js:6476:18
    at Object.gotAccum (http://localhost:8080/__cypress/runner/cypress_runner.js:6465:25
    at Object.tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23
[Open in build log](https://teamcity.haivision.com/buildConfiguration/CineNet4x_Projects_CypressComponents/690401?hideProblemsFromDependencies=false&expandBuildTestsSection=true&hideTestsFromDependencies=false&expandBuildChangesSection=true&showLog=690401_2000000247_2000000247&logFilter=debug)

@werge2121
Copy link

Same for us too

@amir1218
Copy link

amir1218 commented Jan 9, 2024

We have been running into this sporadically when Component testing after migrating from CY 12.x to 13.6.2. Similarly to cases above, it happens towards the end of running a batch of suites (files) together.

Screenshot 2024-01-08 at 5 44 43 PM

Resorted to running cypress with DEBUG='cypress:*'. This is an instance of a crash:

 cypress: server: reporter got mocha event 'test'
with args: [u {
    title: 'An uncaught error was detected outside of a test',
    fn: [Function: o] {
        toString: [Function(anonymous)]
    },
    body: '() => {\n        throw err;\n      }',
    async: undefined,
    sync: undefined,
    _timeout: 2000,
    _slow: 250,
    _enableTimeouts: true,
    timedOut: undefined,
    _retries: -1,
    _currentRetry: 0,
    pending: false,
    type: 'test',
    duration: undefined,
    state: 'skipped',
    parent: p {
        title: '',
        ctx: {},
        suites: [],
        tests: [Array],
        pending: false,
        _beforeEach: [],
        _beforeAll: [],
        _afterEach: [],
        _afterAll: [],
        root: true,
        _timeout: 2000,
        _enableTimeouts: true,
        _slow: 250,
        _bail: false,
        _retries: -1,
        _onlyTests: [],
        _onlySuites: [],
        delayed: false,
        _events: [Object: null prototype],
        _eventsCount: 1,
        file: 'VALID_PATH_TO_FILE_DEDACTED',
        id: 'r1',
        type: 'suite'
    },
    id: 'r2',
    _testConfig: {
        testConfigList: [],
        unverifiedTestConfig: {}
    },
    order: 1,
    invocationDetails: {
        function: 'Object.getInvocationDetails',
        fileUrl: 'http://localhost:8080/__cypress/runner/cypress_runner.js',
        originalFile: 'http://localhost:8080/__cypress/runner/cypress_runner.js',
        line: 97377,
        column: 17,
        whitespace: '    ',
        stack: 'Error\n' + '    at Object.getInvocationDetails 
(http://localhost:8080/__cypress/runner/cypress_runner.js:97377:17)\n' + '    at Suite.addTest 
(http://localhost:8080/__cypress/runner/cypress_runner.js:145737:85)\n' + '    at Object.createRootTest 
(http://localhost:8080/__cypress/runner/cypress_runner.js:145872:21)\n' + '    at Object.normalizeAll 
(http://localhost:8080/__cypress/runner/cypress_runner.js:163115:17)\n' + '    at CDPBrowserSocket.<anonymous> 
(http://localhost:8080/__/assets/index-caf2649c.js:146264:46)\n' + '    at CDPBrowserSocket.on2 
(http://localhost:8080/__/assets/index-caf2649c.js:34575:11)\n' + '    at Emitter2.emit 
(http://localhost:8080/__/assets/index-caf2649c.js:34616:24)\n' + '    at http://localhost:8080/__/assets/index-caf2649c.js:37709:15'

    }
}] + 9 ms

There is a lot in the logs that makes it hard to share but please do let us know if we should be looking for or can share anything useful to help unraveling this.

@cubanx
Copy link

cubanx commented Jan 10, 2024

Does anyone know of a way to suppress this error until we can get a resolution?

@rbecheras
Copy link

We have a very similar issue with another file: node_modules_core-js_modules_es_array_concat_js-node_modules_babel_runtime_helpers_esm_define-ec4858

1) An uncaught error was detected outside of a test

  0 passing (433ms)
  1 failing

  1) An uncaught error was detected outside of a test:
     ChunkLoadError: The following error originated from your test code, not from Cypress.

  > Loading chunk node_modules_core-js_modules_es_array_concat_js-node_modules_babel_runtime_helpers_esm_define-ec4858 failed.
(error: http://localhost:8080/__cypress/src/node_modules_core-js_modules_es_array_concat_js-node_modules_babel_runtime_helpers_esm_define-ec4858.js)

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

It makes our test suite pass sometimes but fail randomly and frequently, on a component or another, randomly.

@jennifer-shehane jennifer-shehane added the CT Issue related to component testing label Jan 17, 2024
@benpatterson
Copy link
Member

I'm leaving behind some notes after digging into this further.

We are experiencing this error on ~9% of our component test builds. (I can't remember offhand how many tests that entails.)

Indeed error messages above are consistent with what we see, here's an excerpt (with a slight edit on chunk name tbh):

  1) An uncaught error was detected outside of a test:
     ChunkLoadError: The following error originated from your test code, not from Cypress.

  > Loading chunk name1-name2-file~spec-11~spec-14~spec-15~spec-17~spec-22~spec-23~spec-25~spec-27~spec-28~43d59dbf failed.

It includes the localhost path as well on the next line (which I left out here).

Noteworthy...going up a few lines in the build, we are seeing something like this (I changed more file names out of caution):

  Running:  dir/myComponentSpec.spec.tsx                                                  
  Estimated: 1 second


ℹ 「wdm」: Compiling...
  (Attempt 1 of 3) An uncaught error was detected outside of a test
ℹ 「wdm」: wait until bundle finished: /<root+directory>/related-file~spec-34.js
ℹ 「wdm」: wait until bundle finished: /<root+directory>/related-file.js
  (Attempt 2 of 3) An uncaught error was detected outside of a test
  1) An uncaught error was detected outside of a test

It appears to me that the ChunkLoadError occurs because the next test is running before webpack compilation is completed on the devserver. I think this includes related CSS compilations, but honestly I don't know if that's all the time or a subset of examples.

Ultimately I'm convinced the next test needs to wait until compilation completes and the devserver has updated the cache. I attempted to set devserver settings around hot reload, etc, but those didn't work -- likely because the test is still trying to serve the page and is not waiting for the devserver to signal it's up to date.

When it comes to waiting for compilation to complete, we do have logic around this in CypressCTWebpackPlugin in this function. As-written, it's awaiting specs, and this is why I'm wondering if we need something to wait for related assets, too. Regardless, I think we need a way of ensuring all compilation completes, including any styling, before proceeding to the next test.

There had been a previous PR that leveraged the webpack devserver's index HTML file, which I believe would yield the result I'm thinking of (change here). That PR was intended to fix a situation specific to MacOS version, but I'm optimistic it could resolve the ChunkLoadError. The PR was merged but the code in the file today is older than the PR, so I don't know if it was rolled back at a later time.

@hogatejon
Copy link

Just commenting to say I am also experiencing this issue. Have traced it down to being introduced by 12.17.4, any version below this seems to be completely fine on our CI runs.

@jennifer-shehane
Copy link
Member

Found this in our own tests: https://cloud.cypress.io/projects/ypt4pf/runs/53776/overview/c7135bc3-5fcb-4555-8497-c7b93658a628?roarHideRunsWithDiffGroupsAndTags=1

@jennifer-shehane
Copy link
Member

We're spiking into this to see if we can find what's causing this.

@jennifer-shehane jennifer-shehane added stage: investigating Someone from Cypress is looking into this and removed stage: needs information Not enough info to reproduce the issue labels Feb 5, 2024
@TomaszG
Copy link
Contributor

TomaszG commented Feb 6, 2024

Same here. Since the v12 upgrade (I don't recall what the version was, though), we have gotten this on GitHub Actions CI sometimes. My initial thought was that it was caused by the first spec in our test suite. However, changing the order of suites didn't help. It's just that the first spec fails.

My workaround for this was to amend the run script:
cypress run --component --spec './**/OurFirstSpec.cy.js' || true && cypress run --component
So, the first attempt could fail, but the second run was 100% successful. Since upgrading from 13.6.3 to 13.6.4, the second run also fails for around 30% of runs.

Cypress 13.6.4
Node.js 21.6.1
NextJS 14.1.0

BTW, this seems to be related or even the same: #16421

@AtofStryker
Copy link
Contributor

AtofStryker commented Feb 7, 2024

Hey all. Sorry for the delay on an update here. I've been investigating the issue heads down for about a week now. I'm able to reproduce the error on my end but only at the start of the run and sparingly in the middle of the run. I think there are two issues possibly going on here

At the start of the run

At the end of webpack compilation, the dev-server:compile:success event is emitted by the cypress webpack dev server, but nothing is actively listening to this event. The only exception is watchForChanges being enabled inside the SocketCT handler inside the Cypress server, which is unset in run mode and isn't applicable here.

In other words, we can get ourselves into a race condition where webpack takes a long time to build all assets, but the cypress run has begun and is able to resolve the index.html chunk, but not other chunks in the test because they are not present in the output directory. That is what is happening in this example:

support_file_fallover_with_retries

In the middle of a run

Adding to what @benpatterson mentioned and a bit more complicated to reproduce, but does happen, is webpack-dev-server recompiling in the middle of a test. We can see something like this here with some logging I added in this diagnostic binary.

Test starts. Something triggers webpack-dev-server to recompile. test fails with chunk error

1

Just in time recompile (just by chance) while the browser is relaunching for the second test to run. second test passes

2

For this, it seems like the dev-server is watching assets and recompiling. What I need to further investigate is

  • what is being compiled here and does it need to be compiled? Maybe something configuration-wise changed in the webpack.config from version 4 to 5.

Waiting for the dev server to compile is a bit tricky as it can trigger a compilation at any time, but if we can answer the above question, it puts us in a better position to solve the problem correctly.

Some questions that might be helpful for us in fixing the issue

  • Does the error happen at the beggining of the cypress run or in the middle? It sounds like the first case for @TomaszG where compilation fails in the beginning of the test and the second case for @benpatterson where the test fails in the middle. I am curious with others running into this issue where it is happening for you.
  • What are the stats on your webpack build? Any idea how long it is taking for webpack to recompile?
  • if willing, we have a diagnostic binary build here (this is not a fix) that you can install and run with the following flags CYPRESS_INTERNAL_BROWSER_CONNECT_TIMEOUT=120000 DEBUG='cypress:server:open_project,cypress:webpack-dev-server:CypressCTWebpackPlugin npx cypress run --component ... which might give us an idea what webpack is doing under your test.

I will give more updates as soon as I have them. I appreciate everyones patience with the issue resolution.

@TomaszG
Copy link
Contributor

TomaszG commented Feb 8, 2024

@AtofStryker, great investigation and summary. I can confirm that the error happens only at the beginning of the run for me; I haven't noticed it in the middle. I also haven't noticed any webpack re-compilation in the middle of the run.

The compilation times on CI are around 19 seconds for the first run (which is allowed to fail) and 14 seconds for the second run.

@AtofStryker
Copy link
Contributor

@bene-starzengruber @cubanx @werge2121 @amir1218 @rbecheras @TomaszG what version of webpack-dev-server are you all using? It should be pretty easy to tell with either in your package.json or from debugging with cypress via DEBUG=cypress:webpack-dev-server:devServer npx cypress run --component ...

I think the recompiling in the middle is related to either a bug or a misconfiguration within webpack-dev-server@3 . The documentation is difficult to find since v3 hasn't been released or maintained for about 3 years, but from what I can see everything looks configured correctly on our end. Updating to webpack-dev-server@4 seems to resolve the issue of the mid run recompilation. Cypress ships with webpack-dev-server@4 with @cypress/webpack-dev-server unless you explicitly install v3

@TomaszG I would be curious if using the diagnostic binary while setting CYPRESS_INTERNAL_BROWSER_CONNECT_TIMEOUT=120000 resolves your issue of the initial chunk load error failure if you have a chance to use it.

@werge2121
Copy link

werge2121 commented Feb 9, 2024

We should just be using the default devserver that comes with cypress, so 4. For us its happening in the middle of the run usually. It takes around 5-6 seconds for the webpack to compile usually.

@cwillsea-mtg
Copy link

My team is using the default dev server that comes with cypress:

  component: {
    devServer: {
      bundler: 'webpack',
      framework: 'next',
    },
  },

The errors seem to always happen at the start of a test file, but pop up in random places in our test suite. For example, here is a recent failure in the 73th test file out of a suite of 90 where the other 89 runs all passed (edited to remove component/file names):

  Running:  components/COMPONENT_NAME.cy.tsx                          (73 of 90)


  1) An uncaught error was detected outside of a test

  0 passing (665ms)
  1 failing

  1) An uncaught error was detected outside of a test:
     ChunkLoadError: The following error originated from your test code, not from Cypress.

  > Loading chunk vendors-node_modules_SOME_STRING.js failed.
(error: http://localhost:8080/__cypress/src/vendors-SOME_STRING.js)

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
      at __webpack_require__.f.j (http://localhost:8080/__cypress/src/webpack.js:340:29)
      at <unknown> (http://localhost:8080/__cypress/src/webpack.js:137:40)
      at Array.reduce (<anonymous>)
      at __webpack_require__.e (http://localhost:8080/__cypress/src/webpack.js:136:67)
      at Object.load (http://localhost:8080/__cypress/src/main.js:485:577)
      at <unknown> (http://localhost:8080/__cypress/runner/cypress_runner.js:110819:21)
      at tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23)
      at Object.gotValue (http://localhost:8080/__cypress/runner/cypress_runner.js:6476:18)
      at Object.gotAccum (http://localhost:8080/__cypress/runner/cypress_runner.js:6465:25)
      at Object.tryCatcher (http://localhost:8080/__cypress/runner/cypress_runner.js:1807:23)


  (Results)

  ┌────────────────────────────────────────────────────────────────────────────────────────────────┐
  │ Tests:        1                                                                                │
  │ Passing:      0                                                                                │
  │ Failing:      1                                                                                │
  │ Pending:      0                                                                                │
  │ Skipped:      0                                                                                │
  │ Screenshots:  1                                                                                │
  │ Video:        false                                                                            │
  │ Duration:     0 seconds                                                                        │
  │ Spec Ran:     components/COMPONENT_NAME.cy.tsx                             │
  └────────────────────────────────────────────────────────────────────────────────────────────────┘

The frequency with which these errors occur has been increasing as we add more test files. If there's any debug/diagnostic config we can set to get more info happy to try as this issue is happening frequently in our CI

@anilanar
Copy link

anilanar commented Feb 13, 2024

@AtofStryker

It would be great if cypress team would develop a pre-bundle option for runs in the CI. We had similar issues with MSW in our component tests. Browser stops trying when a service worker script takes more than ~60 seconds to load. We had to slightly modify the default dev server to "prebuild" service worker file so that when it's actually needed, it's already built and is ready to serve by the dev server:

    devServer: async ({ specs, cypressConfig, devServerEvents }) => {
      const result = await devServer({
        specs,
        cypressConfig,
        devServerEvents,
        webpackConfig,
      });
      // trigger a build for MSW so that it doesn't time out
      // in CI when trying to initialize msw
      await fetch('http://localhost:8080/mockServiceWorker.js');
      return result;
    },

So if there were an option to pre-bundle everything, flaky tests due to middle of the run builds taking too long would be long gone.

In user land, this can be achieved by manually pre-bundling and then by creating a custom dev-server that serves pre-bundled files. But it's not very elegant, Cypress team can do better by introducing a new config for pre-bundling.

@AtofStryker
Copy link
Contributor

Hey all. Just a few updates.

Mid recompilation with webpack-dev-server has stopped with the update from v3 to v4, which is great! However, we are still hitting ChunkLoadErrors 🙁 .

This issue has been extremely challenging to reproduce, but we have a few theories. My guess is that there are chunk loading issues associated with the main bundle mainly due to us bundling every component test, regardless of what is used under test. The only exception to this is if the --spec option is leveraged to pass in specs. For example:

  • if cypress open is used to to develop a single component test and there are 39 other component tests, ALL 40 component tests are compiled when the app is launched.
  • If cypress run is used to test all specs, ALL component tests are compiled before the tests are initialized.
  • If cypress run is used to test multiple specs via the --parallel flag in CI, ALL component tests are compiled before the tests are initialized, regardless of what tests are run.
  • If cypress run is used to test a single spec via the spec argument, ONE single spec is compiled before the test is run.
  • If cypress run is used to test multiple specs via the spec argument, ONLY THE SPECS PASSED IN are compiled before the test is run.

The larger N is in this case (our example above was 40), the worse the dev server scales as far as building is concerned. Each spec is considered its own entry point in webpack. We don't have proof that reducing the bundle size would fix the chunk errors, but I think this is in large part of the problem as this seems to happen mostly in projects where there are dozens of CT tests.

In most cases, even if the build takes minutes, cypress waits for the dev server to return a response before executing tests. @anilanar In other words, we are pre-bundling everything needed under test already but the assets are not loaded into the browser all at once, which might explain the service worker issue you are running into and I'm glad you were able to find a solution! Something is causing the chunk to fail to load meaning it either doesn't exist, or it timed out loading. Since the assets are held in memory, it is difficult to figure out which has occurred. Either way, I am not convinced flaky tests are due to builds taking too long.

What we are trying internally with one of our projects where this error happens frequently, is to leverage the --spec option to group our tests under execution and use circleci to split the tests per container (@cwillsea-mtg this might be something you can try depending on your setup and would be great feedback for us if it lessens or resolve the issue for you). This will only bundle the assets needed under test, reducing the chunk and bundle sizes under test and likely the stress to load them into memory. This could give us direction on if we need to change some aspects of the dev server depending on whether ChunkLoadErrors continue to surface or not and our ability to tune them. I will report back when I gather more data/information.

@cubanx
Copy link

cubanx commented Feb 14, 2024

@AtofStryker We are using whatever webpack-dev-server comes with Cypress, so I assume it is version 4.

I concur that it seems large tests suites seem to cause this issue. To both speed up our test runs and reduce the frequency of this error, I have some PowerShell scripts that use the --spec parameter to split up the test suite and run a subset of our component tests in parallel.

This reduced the number of test per run from ~1500 to ~400 per run, and the error seems to have abated.

If this helps at all, even running interactively, if we load all our Component tests and then try to run them, there is a significant delay between update/reloads or if you switch test files.

I use another PowerShell script to modify the specPattern inside the cypress.config.ts to limit the number of tests I'm running interactively to just a handful. It's helpful both for speed ups of test reloading and to reduce the test clutter since we have so many.

We also tried switching the Component Server in the past to vite. The interactive tests became too slow to use. We are currently running in a bifurcated fashion, with the full up dev server running vite, but the Component Tests running webpack.

I am actually about to leave the current position I'm in, but if there's any diagnostics or info that would help you, I'll be here until March 1st.

Thanks for your work on this!

@anilanar
Copy link

anilanar commented Feb 14, 2024

@AtofStryker Webpack supports lazy loading with async chunks (code splitting) therefore it is definitely possible to make a test suite start downloading and bundling stuff in the middle of the run. Webpack dev server doesn't initiate building an async chunk unless that chunk is requested by the client with an async import.

This issue can be solved with pre-bundling. It can probably be solved without pre-bundling too, if there is a way for webpack dev server to report any async chunks it finds during a build. Then those async chunks can be requested manually (like I did with the service worker) to manually trigger a build for them before running a test. Keep in mind that this needs to be done recursively, until no async chunks are left.

Another idea is to disable code splitting, e.g. https://webpack.js.org/plugins/limit-chunk-count-plugin/

I'm not really sure if this has anything to do with your ChunkLoadErrors though. What I know is, if an async import fails, it will reject with a ChunkLoadError.


A simple test that downloads an async chunk in the middle of the run:

export const Example = () => {
    const [done, setDone] = useState(false);
    return (
        <button
            onClick={async () => {
                await import("./path-to-something-very-slow-to-bundle");
                setDone(true);
            }}
        >
            {done ? "DONE" : "Click me to download async chunk"}
        </button>
    );
};
it('will download async chunk', () => {
  cy.mount(<Example />);
  cy.get('button').click();
  cy.contains('DONE').should('be.visible');
});

Edit: I still think it's better to pre-bundle and run cypress without a dev server and without a file watcher and without no recompiles for CI use cases; instead of trying to fight file watcher/unnecessary rebuilds that can be caused by myriads of webpack plugins (and potentially unintentional bugs in them). I think using dev-server on CI is picking a wrong fight. Consider this: no build tool or no test tool runs in watch mode on CI. So cypress is opening a can of worms by running in watch mode.

@amir1218
Copy link

@AtofStryker We are on webpack-dev-server 4.15.1

@werge2121
Copy link

Any updates?

@anilanar
Copy link

anilanar commented Feb 22, 2024

Try this workaround, as I previously suggested:

// cypress.config.js

const { defineConfig } = require('cypress');
const { devServer } = require('@cypress/webpack-dev-server');

module.exports = defineConfig({
    ...
    devServer: async ({ specs, cypressConfig, devServerEvents }) => {
      const result = await devServer({
        specs,
        cypressConfig,
        devServerEvents,
        webpackConfig,
      });
      // prebuild files that can cause test failures when they take too long
      // during runs
      await Promise.all([
        fetch('http://localhost:8080/__cypress/src/cypress-support-file.js'),
        // prebuild any other file, such as service workers here 
      ]);
      return result;
    },
});

If other async chunks are causing middle-of-the-run builds, then try using https://webpack.js.org/plugins/limit-chunk-count-plugin/ and limit your chunk count to 1. Or try turning off chunk splitting, see https://webpack.js.org/plugins/split-chunks-plugin/#optimizationsplitchunks .

Again, I doubt this is a misconfiguration in webpack dev server. Async chunks are normal things that optimize initial bundle size by lazy loading things later. They are usually caused by async imports, but if you don't have an async import on your side or if you don't know what that even means, then it must be used by one of the libraries you use.

This is a problem with async chunks triggering builds and those builds not finishing before test times out.

The solution is one of:

  1. disable all async chunks (see https://webpack.js.org/plugins/split-chunks-plugin/#optimizationsplitchunks). Do a build with the same webpack config and make sure webpack produces a single js file.
  2. cypress's dev server integration reads async chunks found by webpack dev server and trigger a build for them (with webpack compiler api or simply by triggering a fetch). Webpack dev server might find new async chunks in those async chunks, so they must be prebuilt too until no async chunk is left.
  3. cypress allows us to prebundle everything (e.g. do a build for all components) and use those prebuilt assets, e.g. by replacing webpack dev server with a simple http server that serves those static files.

Edit: typo

@TomaszG
Copy link
Contributor

TomaszG commented Feb 22, 2024

@AtofStryker I've tried what you've recommended, so I've set CYPRESS_INTERNAL_BROWSER_CONNECT_TIMEOUT=120000 and also used your diagnostic binary based on 13.6.5 and after a couple of runs, it seems that there are no failures. Here's the log output from the tests:

    cypress:webpack-dev-server:start using webpack-dev-server v4 +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile projectRoot: /home/runner/work/<REDACTED>/apps/client +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile supportFile: /home/runner/work/<REDACTED>/apps/client/cypress/support/component.js +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile indexHtmlFile: cypress/support/component-index.html +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile: compile hooks not registered. Invoking callback. +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin addCompilationHooks +45ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin addCompilationHooks: Webpack 5 detected +5ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile +25ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile projectRoot: /home/runner/work/<REDACTED>/apps/client +14ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile supportFile: /home/runner/work/<REDACTED>/apps/client/cypress/support/component.js +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile indexHtmlFile: cypress/support/component-index.html +0ms
  <i> [webpack-dev-server] Project is running at:
  <i> [webpack-dev-server] Loopback: http://127.0.0.1:8080/
  <i> [webpack-dev-server] Content not from webpack is served from '/home/runner/work/<REDACTED>/apps/client/public' directory
    cypress:webpack-dev-server:devServer Component testing webpack server 4 started on port 8080 +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin beforeCompile: compile hooks registered, filtering out files that have been removed by the file system but not yet detected by the onSpecsChange handler +53ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin invoking callback +0ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin addCompilationHooks +7ms
    cypress:webpack-dev-server:CypressCTWebpackPlugin addCompilationHooks: Webpack 5 detected +0ms
  We detected that you have versions of dependencies that are not officially supported:
  
   - `next`. Expected ^10.0.0 || ^11.0.0 || ^12.0.0 || ^13.0.0, found 14.1.0.
  
  If you're experiencing problems, downgrade dependencies and restart Cypress.
  
    cypress:webpack-dev-server:webpack projectRoot: /home/runner/work/<REDACTED>/apps/client, files: <REDACTED> +0ms
  
  ====================================================================================================
  
    (Run Starting)
  
  tput: No value for $TERM and no -T specified
    ┌────────────────────────────────────────────────────────────────────────────────────────────────┐
    │ Cypress:        13.6.5                                                                         │
    │ Browser:        Electron 114 (headless)                                                        │
    │ Node Version:   v21.6.2 (/opt/hostedtoolcache/node/21.6.2/x64/bin/node)                        │
    │ Specs:          34 found (<REDACTED>)                                                          │
    │ Searched:       **/*.cy.{js,jsx,ts,tsx}                                                        │
    │ Experiments:    experimentalWebKitSupport=true                                                 │
    └────────────────────────────────────────────────────────────────────────────────────────────────┘
  
  
  ────────────────────────────────────────────────────────────────────────────────────────────────────
                                                                                                      
    Running:  <REDACTED>.cy.js                                                               (1 of 34)
    cypress:webpack-dev-server:CypressCTWebpackPlugin compiler hooks done. emitting "dev-server:compile:success" to start the runner +37s
  98 assets
  5238 modules
  client (webpack 5.86.0) compiled successfully in 37206 ms

I wonder if it's OK that compiler hooks done is logged after the run starts...

@AtofStryker
Copy link
Contributor

@rgala are you referencing @cypress/webpack-dev-server inside your cypress config as well to verify the correct package is being used? The one that gets used by default lives inside the binary so it really can't be patched. Similar to this:

import { devServer } from '@cypress/webpack-dev-server'

export default {
  component: {
     devServer: (devServerConfig) => {
      return devServer({
        ...devServerConfig,
        framework: 'react',
        bundler: 'webpack',
      })
  }
}

@rgala
Copy link

rgala commented Oct 16, 2024

Sorry @AtofStryker, I did not know I had to make such change. Anyway, after implementing it I have been unable to reproduce the issue anymore and this is good news :)

@jennifer-shehane
Copy link
Member

We intend to make the just-in-time compile flag default within Cypress 14, with a justInTimeCompile configuration option to opt out of the behavior. Followup story here: #30234

@papatelst
Copy link

papatelst commented Oct 16, 2024

@AtofStryker following up on the issue I reported related to End-to-End testing (NOT component testing) in the comment in this ticket in march here.
We are now seeing this error more frequently even outside of after each hook. Its completely random.
If I upgrade cypress version to 13.15.0 (latest) and set experimentalJustInTimeCompile=true in *.config.ts file, as mentioned here, will it cause this random error to go away for our E2E Tests. This flag is more for component tests and not sure if it has any effect on the E2E tests. We dont run component tests from our cypress repo.
If this flag is not useful in our case, then what should we do fix this random ChunkLoadError shown in snapshot in previous comment. We have been seeing this error since upgrade to cypress version 13.5.1. Is this something we need to work with our frontend dev team as the error says -

ChunkLoadError: The following error originated from your application code, not from Cypress. It was caused by an unhandled promise rejection.
  > Loading chunk 69 failed.

@AtofStryker Can you please answer this ? Your previous response can be seen here. Thanks

@smalott16
Copy link

smalott16 commented Oct 17, 2024

I am experiencing this issue in gitlabci on 13.15.0. I found referencing the @cypress/webpack-dev-server in my config file worked some of the time. Usually the test suite would pass the first time but then fail if I re-ran it. I then tried the JIT compile flag which seemed to make the the ChunkErrors go away but then I started getting FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory and my tests would just hang but I imagine is more related to my application and could be remedied through allocating more memory. But anyway for curiosity sake I also tried applying this patch and now it seems to be consistently passing.

So in the end im not even using the experimental JIT flag. But I'm not super familiar with webpack so I'm a little unsure about what this is actually doing or if there could be negative ramifications.

@amir1218
Copy link

We're on 13.14.0 and since the upgrade we have not had any more occurrences of chuck load error. Sounds like we should hold off on 13.15?

@AtofStryker
Copy link
Contributor

We're on 13.14.0 and since the upgrade we have not had any more occurrences of chuck load error. Sounds like we should hold off on 13.15?

13.15.0 is fine to install . There was an install mistake made above that installed 13.5.0 by accident, which was missing the experimental flag which is why the chunk load errors re appeared.

@TomaszG
Copy link
Contributor

TomaszG commented Oct 30, 2024

With larger codebases, the experimentalJustInTimeCompile=true makes the whole execution time even 3x longer. This is a case in our project where we test larger components with multiple specs. Because now webpack compilation runs before each spec, the total execution time growth from ~550s to ~1400s for the whole suite.

@AtofStryker
Copy link
Contributor

With larger codebases, the experimentalJustInTimeCompile=true makes the whole execution time even 3x longer. This is a case in our project where we test larger components with multiple specs. Because now webpack compilation runs before each spec, the total execution time growth from ~550s to ~1400s for the whole suite.

@TomaszG Execution time is going to vary on several factors, but in some cases it is completely reasonable to expect longer execution times. Are you leveraging any type of smart orchestration features, like parallelization to speed up the total run time? Most importantly, are the chunk load errors still present with experimentalJustInTimeCompile=true

@rgala
Copy link

rgala commented Oct 30, 2024

@AtofStryker Will the patch solution you provided be implemented in future versions or I should stick to it as long as it helps with my Azure builds?

@AtofStryker
Copy link
Contributor

@AtofStryker Will the patch solution you provided be implemented in future versions or I should stick to it as long as it helps with my Azure builds?

@rgala I would stick to using the patch for now. We are currently discussing solutions as the sourcemaps do provide value in the Cypress Reporter for error code frames (where your test failed) as well as in test replay

@papatelst
Copy link

@AtofStryker Can you please answer this question incase you have missed ?

@AtofStryker
Copy link
Contributor

@AtofStryker Can you please answer this question incase you have missed ?

Sorry @papatelst I must have missed it. The experimentalJITCompile flag won't have an effect on e2e tests. How large is your spec that you are running in your e2e tests?

@papatelst
Copy link

papatelst commented Oct 31, 2024

@AtofStryker Can you give me exact steps on how to answer your question ? On one of the specPattern used, I see following in console when ran locally
image
The cypress runner shows 168 matches as seen in snapshot below
image
Not sure if I answered your question.

We also saw this error in a cypress run with specPattern which returns 37 spec files. Not sure if this has to do with the number of spec files found during cypress run or not.

@AtofStryker
Copy link
Contributor

@AtofStryker Can you give me exact steps on how to answer your question ? On one of the specPattern used, I see following in console when ran locally image The cypress runner shows 168 matches as seen in snapshot below image Not sure if I answered your question.

We also saw this error in a cypress run with specPattern which returns 37 spec files. Not sure if this has to do with the number of spec files found during cypress run or not.

I think what I am moreso wondering is how many tests are in that spec file that is problematic. Is it always the same spec file or does it happen with others as well?

Are you able to create a separate issue as well against the Cypress repo? I believe what you are experiencing is going to be outside the realm of chunk load errors related to CT testing with webpack

@papatelst
Copy link

@AtofStryker It happens randomly with random spec files. It does not happen with same spec files.
Should I open a separate issue against cypress repo ?

@AtofStryker
Copy link
Contributor

@AtofStryker It happens randomly with random spec files. It does not happen with same spec files. Should I open a separate issue against cypress repo ?

If it's happening with end to end test then I would open a separate issue

@TomaszG
Copy link
Contributor

TomaszG commented Nov 12, 2024

With larger codebases, the experimentalJustInTimeCompile=true makes the whole execution time even 3x longer. This is a case in our project where we test larger components with multiple specs. Because now webpack compilation runs before each spec, the total execution time growth from ~550s to ~1400s for the whole suite.

@TomaszG Execution time is going to vary on several factors, but in some cases it is completely reasonable to expect longer execution times. Are you leveraging any type of smart orchestration features, like parallelization to speed up the total run time? Most importantly, are the chunk load errors still present with experimentalJustInTimeCompile=true

Yes, we do run the tests in parallel and component tests run takes significantly longer, especially on CI. Given that webpack bundle doesn't change during the test execution, I don't see a reason of involving webpack bundle for each spec, as that's a major performance drawback, especially when testing complex enterprise apps. I recon that a simple wait (even static if there's no milestone on which you could rely) for webpack to finish or a one-time retry in case of ChunkLoadError would make the error gone for most of the users.

@niksumeiko
Copy link

What I found out is that Cypress ignores the config.retries configuration when the Loading chunk X failed error is thrown:

The following error originated from your test code, not from Cypress.

  > Loading chunk 5 failed.
(error: http://localhost:8080/__cypress/src/5.js)

I tried to configure retries in different ways, but it's not retrying:

export default defineConfig({
    retries: {
        experimentalStrategy: 'detect-flake-and-pass-on-threshold',
        experimentalOptions: {
            maxRetries: 2,
            passesRequired: 1,
        },
        runMode: true,
        openMode: false,
    },
    component: {
        

Can't we make it to retry the component test on such an error? Not only on a flaky test.

Perhaps, in the next retry attempt, the chunk is already there (compilation finishes).

@AtofStryker
Copy link
Contributor

What I found out is that Cypress ignores the config.retries configuration when the Loading chunk X failed error is thrown:

The following error originated from your test code, not from Cypress.

  > Loading chunk 5 failed.
(error: http://localhost:8080/__cypress/src/5.js)

I tried to configure retries in different ways, but it's not retrying:

export default defineConfig({
    retries: {
        experimentalStrategy: 'detect-flake-and-pass-on-threshold',
        experimentalOptions: {
            maxRetries: 2,
            passesRequired: 1,
        },
        runMode: true,
        openMode: false,
    },
    component: {
        

Can't we make it to retry the component test on such an error? Not only on a flaky test.

Perhaps, in the next retry attempt, the chunk is already there (compilation finishes).

It's likely more difficult to do in this case because the chunk is likely failing to load due to resource constraints and likely retrying to load it will not work. Have you tried the experimentalJustInTimeCompile option? We are making this the default in Cypress 14

@shentao
Copy link

shentao commented Dec 11, 2024

@AtofStryker Enabling experimentalJustInTimeCompile fixed the issue in our case. However, I don't feel like making it the default solution is a good move. At least not without addressing some issues first.

In larger projects, it causes major slowdowns in test execution on CI and increased memory requirements. We now have to run 6 GB RAM machines, instead of 4 GB, to stay stable, which is 1.5x as expensive on providers like CircleCI. This makes a pretty significant difference in our CI budget, given the sheer number of component tests we run.

As much as we'd like to stay with Cypress, the ever-increasing memory requirements and instability are really putting into question whether investing in component tests was a good idea to begin with, compared to something like Vittest.

Have you considered migrating to a webpack alternative, while maintaining the ability to mock/stub imports? Could that make the JIT part easier on the memory and time?

@jennifer-shehane
Copy link
Member

@shentao Just want to note that the justInTimeCompile configuration will be available to opt out of in Cypress 14 if needed.

@AtofStryker
Copy link
Contributor

Yes, we do run the tests in parallel and component tests run takes significantly longer, especially on CI. Given that webpack bundle doesn't change during the test execution, I don't see a reason of involving webpack bundle for each spec, as that's a major performance drawback, especially when testing complex enterprise apps. I recon that a simple wait (even static if there's no milestone on which you could rely) for webpack to finish or a one-time retry in case of ChunkLoadError would make the error gone for most of the users.

@TomaszG We initially tried this when exploring options for a solution here. The problem is the assumption that the ChunkLoadError can be reconciled and that repeatedly calling the entrypoint would eventually fix this. Depending on your webpack configuration, it could, but it doesn't always work unfortunately and is extremely error prone because usually the reason the chunk is failing to load is the dev server eating too much memory and resources because of how large the bundle is. Often, the process completely stalls. At least this is what I saw when using one of our really large projects internally and resource constrained machines.

Another solution could be to pre-bundle similar to what @anilanar did in #28644 (comment). To their point, we have seen that source maps, depending on the Component Testing test harness, can be quite large and can additionally lead to memory problems (see #28644 (comment)). We want to possibly add the option to disable source maps in CI in the future along with adding some tools to better help diagnose user issues (see #30461).

We are hoping with experimentalJustInTimeCompile that we can allow users to better horizontally scale with the option on where users can leverage smart orchestration for really large enterprise projects so the time is not a significant factor. We have seen significant improvements on our end when leveraging this.

@shentao
Copy link

shentao commented Dec 11, 2024

@jennifer-shehane I know, I've been following this thread for a long time now. The problem is that, with experimentalJustInTimeCompile disabled, most of the component tests become unstable after upgrading to Cypress v13. Our QA engineers value Test Replay for e2e tests, which is why we wanted to upgrade to v13. So while e2e tests DX has improved, it messed up with Component tests making them completely unreliable up until you added experimentalJustInTimeCompile. But that came with a compute tax.

@shentao
Copy link

shentao commented Dec 11, 2024

We are hoping with experimentalJustInTimeCompile that we can allow users to better horizontally scale with the option on where users can leverage smart orchestration for really large enterprise projects so the time is not a significant factor. We have seen significant improvements on our end when leveraging this.

@AtofStryker That's something that CI providers often provide out of the box (load balancing tests based on timings). It might help with the overall time, but it does nothing to help with the budget side of things. Throwing more machines at the problem should not be the only solution to a performance problem like this. Even if it is the simplest way to go around it, compute is ultimately not free. Unless of course, Cypress starts offering alternative hosted CI runners where clients can pay on a per test basis rather than per compute minutes.

@AtofStryker
Copy link
Contributor

@shentao Just to be clear are you saying you were using 4GB machines before JIT was released and now you are up to 6 GB? I find it hard to believe that JIT would take more memory than the default implementation. That would suggest there is a memory leak someplace and I would be curious to investigate with some type of reproduction.

To your point, compute is not free, but horizontal scaling gives you options depending on what you need. We can only work with the vertical limit we are given, which is webpack dev server's ceiling to host very large bundles. The lower (or lowest) we can make that vertical ceiling, the better scale options we can allow users to partake in. It gives consumers a choice to possibly use one large machine, or several smaller ones in parallel. Or having the option on with no chunk errors on a single machine, but the tests take a long time to complete . Compute may be cheaper, but the tests could take longer to run. It's a sliding scale on how the consumer wishes to orchestrate their CI based on what factors matter most to them in the tradeoff: compute cost vs time for tests to complete.

To be clear, you do not have to use Webpack with Component Testing if you do not wish to. We fully support Vite to bundle your components and run them in the browser. Our vite dev server uses file system references to hydrate components in the browser, which makes it much faster to run generally.

There are many reasons you would want to use some type of browser based component testing which we try to articulate in this blog post, but just like anything there are trade-offs, which are most obvious between something like a node context runner like vitest with jsdom, and browser based testing like with Cypress.

@shentao
Copy link

shentao commented Dec 11, 2024

I get that webpack is theoretically not a hard requirement (mentioned that in a comment earlier) except that it is because without it the mocking/stubing functionality is not working with Vite due to the nature of esm. At least that was a problem a few months ago when I last tried to migrate away from using the webpack dev server. That's actually the only reason why we still have webpack in our project - to support Cypress component tests. The app itself is built with Vite. If anything changed in that regard, I'm happy to try migrating again.

I would not rule out a memory leak somewhere – the project consists of almost 2000 Vue components and a similar number of ts and js files. But investigating that is not an easy task as you might imagine.

Don't get me wrong, I've been a proponent of Cypress pretty much since its inception. But the amount of frustration it has been generating for our team over the last years is beginning to be hard to ignore. Of course, a lot of that might come from the pains of a rapidly growing codebase. So please do take my rant with a grain of salt. 😅

edit: we are also using the code coverage plugin for component tests which is contributing to the memory consumption, though I haven't measured exactly by how much.

@mschile mschile added the Cypress 14 Issues scoped for Cypress 14 label Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CT Issue related to component testing Cypress 14 Issues scoped for Cypress 14 experimental: just-in-time-compile stage: awaiting response Potential fix was proposed; awaiting response
Projects
None yet
Development

No branches or pull requests