So I have this Redux action creator that is using redux thunk
middleware:
accountDetailsActions.js:
export function updateProduct(product) {
return (dispatch, getState) => {
const { accountDetails } = getState();
dispatch({
type: types.UPDATE_PRODUCT,
stateOfResidence: accountDetails.stateOfResidence,
product,
});
};
}
How do I test it? I'm using the chai
package for testing. I have found some resources online, but am unsure of how to proceed. Here is my test so far:
accountDetailsReducer.test.js:
describe('types.UPDATE_PRODUCT', () => {
it('should update product when passed a product object', () => {
//arrange
const initialState = {
product: {}
};
const product = {
id: 1,
accountTypeId: 1,
officeRangeId: 1,
additionalInfo: "",
enabled: true
};
const action = actions.updateProduct(product);
const store = mockStore({courses: []}, action);
store.dispatch(action);
//this is as far as I've gotten - how can I populate my newState variable in order to test the `product` field after running the thunk?
//act
const newState = accountDetailsReducer(initialState, action);
//assert
expect(newState.product).to.be.an('object');
expect(newState.product).to.equal(product);
});
});
My thunk doesn't do any asynchronous actions. Any advice?
We use store. getActions() to identify the actions that our thunk has dispatched when it was called. expectedActions is an array which holds the list of actions that the thunk should have called. We pass this to expect() and verify if the actions that the thunk has dispatched are the same as those we had anticipated.
A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which serve as an action log for tests. Please note that this library is designed to test the action-related logic, not the reducer-related one.
Redux Thunkis one of the most popular middlewares for Redux. It allows you to write asynchronous logic that interacts with the store. The complete installation and configuration guide for Redux Thunk is available here. Testing action creators Action creatorsare functions that return plain objects.
How to Write Unit Tests for Asynchronous Redux Thunks in Five Easy Steps 1 Analyze dependencies 2 Define expected behaviours 3 Mock dependencies 4 Implement the tests
The guiding principles for testing Redux logic closely follow that of React Testing Library: The more your tests resemble the way your software is used, the more confidence they can give you. - Kent C. Dodds Because most of the Redux code you write are functions, and many of them are pure, they are easy to test without mocking.
If you prefer, or are otherwise required to write unit tests for your action creators or thunks, refer to the tests that Redux Toolkit uses for createAction and createAsyncThunk. Reducers are pure functions that return the new state after applying the action to the previous state.
How to Unit Test Redux Thunks
The whole point of a thunk action creator is to dispatch asynchronous actions in the future. When using redux-thunk a good approach is to model the async flow of beginning and end resulting in success or an error with three actions.
Although this example uses Mocha and Chai for testing you could quite as easily use any assertion library or testing framework.
Modelling the async process with multiple actions managed by our main thunk action creator
Let us assume for the sake of this example that you want to perform an asynchronous operation that updates a product and want to know three crucial things.
- When the async operation begins
- When the async operation finishes
- Whether the async operation succeeded or failed
Okay so time to model our redux actions based on these stages of the operation's lifecycle. Remember the same applies to all async operations so this would commonly be applied to http requests to fetch data from an api.
We can write our actions like so.
accountDetailsActions.js:
export function updateProductStarted (product) {
return {
type: 'UPDATE_PRODUCT_STARTED',
product,
stateOfResidence
}
}
export function updateProductSuccessful (product, stateOfResidence, timeTaken) {
return {
type: 'PRODUCT_UPDATE_SUCCESSFUL',
product,
stateOfResidence
timeTaken
}
}
export function updateProductFailure (product, err) {
return {
product,
stateOfResidence,
err
}
}
// our thunk action creator which dispatches the actions above asynchronously
export function updateProduct(product) {
return dispatch => {
const { accountDetails } = getState()
const stateOfResidence = accountDetails.stateOfResidence
// dispatch action as the async process has begun
dispatch(updateProductStarted(product, stateOfResidence))
return updateUser()
.then(timeTaken => {
dispatch(updateProductSuccessful(product, stateOfResidence, timeTaken))
// Yay! dispatch action because it worked
}
})
.catch(error => {
// if our updateUser function ever rejected - currently never does -
// oh no! dispatch action because of error
dispatch(updateProductFailure(product, error))
})
}
}
Note the busy looking action at the bottom. That is our thunk action creator. Since it returns a function it is a special action that is intercepted by redux-thunk middleware. That thunk action creator can dispatch the other action creators at a point in the future. Pretty smart.
Now we have written the actions to model an asynchronous process which is a user update. Let's say that this process is a function call that returns a promise as would be the most common approach today for dealing with async processes.
Define logic for the actual async operation that we are modelling with redux actions
For this example we will just create a generic function that returns a promise. Replace this with the actual function that updates users or does the async logic. Ensure that the function returns a promise.
We will use the function defined below in order to create a working self-contained example. To get a working example just throw this function in your actions file so it is in the scope of your thunk action creator.
// This is only an example to create asynchronism and record time taken
function updateUser(){
return new Promise( // Returns a promise will be fulfilled after a random interval
function(resolve, reject) {
window.setTimeout(
function() {
// We fulfill the promise with the time taken to fulfill
resolve(thisPromiseCount);
}, Math.random() * 2000 + 1000);
}
)
})
Our test file
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import chai from 'chai' // You can use any testing library
let expect = chai.expect;
import { updateProduct } from './accountDetailsActions.js'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('Test thunk action creator', () => {
it('expected actions should be dispatched on successful request', () => {
const store = mockStore({})
const expectedActions = [
'updateProductStarted',
'updateProductSuccessful'
]
return store.dispatch(fetchSomething())
.then(() => {
const actualActions = store.getActions().map(action => action.type)
expect(actualActions).to.eql(expectedActions)
})
})
it('expected actions should be dispatched on failed request', () => {
const store = mockStore({})
const expectedActions = [
'updateProductStarted',
'updateProductFailure'
]
return store.dispatch(fetchSomething())
.then(() => {
const actualActions = store.getActions().map(action => action.type)
expect(actualActions).to.eql(expectedActions)
})
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With