Unable to Write Consecutive Component Tests which Navigate to Other URLs
See original GitHub issueCurrent behavior
In the component test runner, when a test runs that clicks a link to another URL/path, the subsequent test fails due to the page’s HTML being in a bad state.
Here is the default HTML response when an interaction with the component changes the URL path to /endpoint
:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /endpoint</pre>
</body>
</html>
Even when using cy.intercept()
to return a custom response, there is no way to return to the original URL the test was running at.
I even tried “hacky” work-arounds such as using cy.go('back')
, but this results in the test runner entering an infinite loop.
The only current workaround appears to be to separate these tests into separate spec files and run each test at the very end of the file.
Desired behavior
In this situation, Cypress should reset the component test runner to the original window.location.href
and not persist the URL/path I visited in a previous test.
Test code to reproduce
Code:
export const MyComponent = () => (
<div>
<a href="/endpoint">Click me!</a>
<p>some text</p>
</div>
)
Test:
describe('MyComponent', () => {
it('clicks a link which brings us to a new URL', () => {
cy.mount(<MyComponent />);
cy.intercept('/endpoint', 'success');
cy.findByRole('link', { name: 'Click me!' }).click();
});
it('I want to test something else about my component now', () => {
cy.mount(<MyComponent />);
cy.findByText('some text').should('be.visible'); // this assertion fails since the DOM is empty
});
});
Cypress Version
10.9.0
Node version
14.19.1
Operating System
macOS 12.6
Debug Logs
No response
Other
No response
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:8 (2 by maintainers)
Top GitHub Comments
I’m going to use this in my workshop tomorrow 😃
Great workaround. Should find it’s way into the docs.
On Fri, Oct 28, 2022 at 3:36 PM Dan Adajian @.***> wrote:
Unfortunately you cannot navigate between pages in Cy component tests unless you’re using an in-memory router that doesn’t change top’s URL. That’s the moment where you’ll want to write an end-to-end test.
I’ve tried many “workarounds” to prevent this top-level navigation, but we decided at the time of building Cypress CT that it was out of scope and that most people can get what they need from using a test-only in memory router, spying on route navigation, and using router hooks to prevent page navigation.
If I come up with a workaround, I’ll let you know.