Reputation: 151
I have an redux action which has an async call to an API.
import { ForbiddenRequest, APIError } from "../errors" import { fetchActionCreator } from "redux-fetch-helpers" export const ADD_CART_ITEMS = "ADD_CART_ITEMS" export default function addCartItems(items, authToken){ return fetchActionCreator({ url: `${API_BASE}/ajax_cart`, //eslint-disable-line no-undef fetchOptions: { method: "POST", headers: new Headers({ "Authorization": `jwt ${authToken}`, "Accept": "application/json", "Content-Type": "application/json", }), body: JSON.stringify(items), credentials: "same-origin", }, actionType: ADD_CART_ITEMS, responseConfig: { 200: (resp => resp), 403: (payload => new ForbiddenRequest(payload)), other: (payload => new APIError(payload)), } }) }
I am trying to mock the fetchActionCreator method by using sinon stubs. This is my spec file
import addCartItems from "../../actions/addCartItems" import sinon from "sinon" describe("The addCartItems action", () => { let fetchActionCreator it("should create an action to add an item into the cart", () => { const addedCartItem = { items: [{product_variant: 10, quantity: 1}] } const expectedAction = { type: "ADD_CART_ITEMS", meta: {sequence: "BEGIN"}} fetchActionCreator = sinon.stub() // fetchActionCreator() fetchActionCreator.returns(expectedAction) expect(addCartItems(addedCartItem, "someToken")).to.equal(expectedAction) }) })
But somehow the function is not getting mocked. Can you suggest me the right way.
Upvotes: 0
Views: 1472
Reputation: 10535
You need to stub the actual function from the library that is being called, not just create a stub that has the same name.
Add the following to your imports in your tests:
import * as reduxFetchHelpers from 'redux-fetch-helpers';
Then to the body of your test, replace your current stub code with:
const fetchActionCreator = sinon.stub(reduxFetchHelpers, 'fetchActionCreator');
fetchActionCreator.returns(expectedAction);
I have not tested this code but it looks like it should work.
Upvotes: 2