Search code examples
javascriptreduxredux-thunknock

Test side effects in Redux actions


I'm working through the Redux tutorial found here.

In the app that I've created, I have an action with a side effect just as the one shown here in the receivePosts function where Date.now() is called.

The side effect is triggered after an async function is completed. When following this async test in my own app. I get a response looking like this:

actual: 
{ 
  type: 'REQUEST_LEAGUE_SUCCESS',
  receivedAt: 1453991947254,
  league: 'Div 3',
  resultsTable: [ [Object], [Object] ] 
},

expected: 
{ 
  type: 'REQUEST_LEAGUE_SUCCESS',
  league: 'Div 3',
  receivedAt: 1453991947235,
  resultsTable: [ [Object], [Object] ]
}

where the date from my expected action is not equal to the date from the actual action. In my expected action, I have the following:

receivedAt: Date.now()

The structure of my code is exactly the same as the code found in the Redux tutorial, apart from my action creator having this side effect.

My question boils down to: How do I handle these side effects to make my tests pass?


Solution

  • Test code that relies on grabbing the current time is not a good idea. You'll need rewrite things so that you can mock out or inject a date. Some good examples of doing that at (Unit Tests, How to Write Testable Code and Why it Matters). That article is C#-based, but the same same concept applies here.