faceyspacey / redux-first-router

🎖 seamless redux-first routing -- just dispatch actions
MIT License
1.56k stars 143 forks source link

Mocking history #342

Open aaaaahaaaaa opened 5 years ago

aaaaahaaaaa commented 5 years ago

Hi. What would be the correct way to mock the history getter in order not to get the following error with jest?

Error: Uncaught [TypeError: Cannot read property 'listen' of undefined]

I tried to use both:

import * as router from 'redux-first-router';

jest.spyOn(router, 'history', 'get').mockImplementation(jest.fn());

Or

Object.defineProperty(router, 'history', {
   value: jest.fn(),
});

But I get the following errors respectively:

TypeError: Cannot redefine property: history

history is not declared configurable

Seems like a very simple problem but I'm struggling there.

ScriptedAlchemy commented 5 years ago

Okay, not sure about mocking them in jest. But I usually just create a new configure store in the test and pass it in an array. Much like when we ssr and the server passes its request path. That’s just an array and you can add more entries to it.

hedgepigdaniel commented 5 years ago

What are you trying to test?

I think the issue is that you are trying to assign to an imported module object, and probably running into a limitation/feature of the object babel etc creates to represent a module with multiple exports. redux-first-router doesn't control what what kind object you get when you do

import * from 'redux-first-router';

If you're trying to test your own app, I can see two options:

  1. You app directly uses the history object. I can't think of a good reason to do that, but if that's the case you can add a dependency injection to your own code, pass in the real history object normally, and pass in a mock history object when you want to mock it.
  2. Your app doesn't directly use the history object. Instead you should probably be writing isolated unit tests, so completely mocking out redux-first-router, e.g. testing reducers, selectors, etc separately with particular actions and states. (plus maybe a few e2e tests in a simulated browser, in which case you wouldn't need to mock out history).