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

Update url without reloading AND have react-router respond #3120

Closed
tnrich opened this issue Jan 10, 2019 · 4 comments
Closed

Update url without reloading AND have react-router respond #3120

tnrich opened this issue Jan 10, 2019 · 4 comments

Comments

@tnrich
Copy link
Contributor

tnrich commented Jan 10, 2019

Does anyone know how to update a route within a cypress test and have a react-router based app change state without refreshing the whole page?

I think because react-router manages its own history object, it doesn't listen to arbitrary URL changes. For example, using window.history.pushState(...) will update the URL without a refresh but the app itself doesn't respond

It seems like I'll need to get access to the history object used by react router within the cypress test itself.

@tnrich
Copy link
Contributor Author

tnrich commented Jan 10, 2019

Okay, I figured out a way to do this but it does require changing my app code:

import React, { Component } from "react";
import { Router } from "react-router-dom";
import AppContentManager from "./AppContentManager";
import { createBrowserHistory } from 'history';

const hist = createBrowserHistory();
if (window.Cypress) {
  window.tgHistory = hist
}

class App extends Component {
  render() {

    return (
      <Router history={hist}>
        <AppContentManager />
      </Router>
    );
  }
}

export default App;

And then for re-usability's sake I can just add a command to use this history everywhere:

/**
 * Goes to a route using react router and **without** reloading the page!
 * @memberOf Cypress.Chainable#
 * @name upload_file
 * @function
 * @param {String} selector - element to target
 */
Cypress.Commands.add("goToRoute", (route="") => {
  return cy.window().its('tgHistory').invoke('push', route)
});

@tnrich
Copy link
Contributor Author

tnrich commented Jan 10, 2019

I'll close this but if someone knows how to do this without changing any app code I'd love to hear it. Thanks!

@tnrich tnrich closed this as completed Jan 10, 2019
@tnrich
Copy link
Contributor Author

tnrich commented Jan 10, 2019

Links
#2059 (not really that relevant)

#128 (very relevant)

@fredrikolovsson
Copy link

Thanks @tnrich, I think this is clean enough. We do the same thing with putting the redux store on window for Cypress, so we can dispatch actions and inspect the state (in the few cases where we need it).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants