How to test reductions that use redux-api-middleware and [CALL_API]?

I have an action called addItemsToCollection that calls the API call like this:

 import {CALL_API} from 'redux-api-middleware'; export function addItemsToCollection(collectionId, itemIds) { return {[CALL_API]: { endpoint: `/collections/${collectionId}/items`, method: 'POST', body: JSON.stringify(itemIds), types: [ ADD_ITEMS, { type: ADD_ITEMS_SUCCESS }, ADD_ITEMS_FAIL ] } }; } 

When I try to write a test just to create this action, for example:

 it('should create an action to add items to a collection', () => { const collectionId = 1; const itemIds = [1,2,3]; const expectedAction = { [CALL_API]: { endpoint: `/collections/${collectionId}/items`, method: 'POST', body: JSON.stringify(itemIds), types: [ ADD_ITEMS, { type: ADD_ITEMS_SUCCESS }, ADD_ITEMS_FAIL ] } }; expect(addItemsToCollection(collectionId, itemIds)).toEqual(expectedAction); }); 

It passes, but this is because it returns an empty {} object for expectAction, as well as from the function of the creator of the action. Not much use.

So my questions are:

Why are empty objects returned?

What is the correct way to conduct this test?

+5
source share
3 answers

CALL_API is a character. They do not appear when passing an object to console.log. If you want to see the key in your object, you can do Object.getOwnPropertySymbols(expectedAction) or you can console.log(expectedAction[CALL_API]) and you will get this object. ( http://exploringjs.com/es6/ch_symbols.html )

You are testing it correctly. If you were to use an empty object, that would not be appropriate. If you use an object with a different character, it will not match.

+1
source

Your expected data should not be calculated because it is part of what you are testing:

 const expectedAction = { [CALL_API]: { endpoint: '/collections/1/items', method: 'POST', body: "[1,2,3]", types: [ ADD_ITEMS, { type: ADD_ITEMS_SUCCESS }, ADD_ITEMS_FAIL ] } }; 

You can end up mocking constants and using raw data.

For your empty objects, this may depend on your imported, mocks testing tools ... There are too many options.

0
source

For those who have this problem, you need to add {apiMiddleware} from redux-api-middleware to your store layout.

0
source

All Articles