3
votes

I'm recently learning Redux and writing Unit Test as part of TDD process using Jest

Im writing test for action creators and reducers. But i'm struggling with: can I make use of action creators in the reducers test?

import * as types from './../../constants/auth';
import * as actions from './../../actions/auth';
import reducer, {initialState} from './../auth';

can I do this

it('should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, actions.loginPending())
    ).toEqual(expectedState)
});

instead of this?

it('should set isFetching to true', () => {
    const expectedState = {
        ...initialState,
        isFetching: true
    }

    expect(
        reducer(initialState, {type: types.LOGIN_PENDING})
    ).toEqual(expectedState)
});

I came to this doubt because the official documentation use hard coded action in the reducers test:

expect(
  reducer([], {
    type: types.ADD_TODO,
    text: 'Run the tests'
  })
).toEqual([{
      text: 'Run the tests',
      completed: false,
      id: 0
}])

I guess using hard coded actions is the best practice isn't?

1

1 Answers

3
votes

Interesting question and I would say it depends how you run your test suite. Personally, I hardcode the actions because if you think about it, they declaratively explain what the reducer is expecting. The argument in favor of importing the actions is that if you ever change their source, the tests will not need to be updated. However, this also means you're expecting your actions to always be correct BEFORE running these tests.

If that's the case (if you always run your actions test suite before this one) then it would be reasonable to import them in your reducer test suite. The only argument against this logic would be that it's not as easy to have a new developer learn how your reducer works by only looking at the reducer test suite as they would also need to look at the actions source file to see what type of actions are dispatched.

On the other hand, hard-coding your actions is more declarative but does require you to update each reducer test if your action changes. The reason I still recommend this approach is that this is that it allows you to send more controlled data but I do agree that it increases maintenance costs.