我有一个redux动作,它对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)), } }) }
我试图通过使用sinon存根来模拟fetchActionCreator方法。 这是我的spec文件
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) }) })
但不知何故,这个功能并没有被嘲笑。你能以正确的方式建议我吗?
答案 0 :(得分:2)
您需要从正在调用的库中存根实际函数,而不仅仅是创建一个具有相同名称的存根。
在测试中将以下内容添加到导入中:
const fetchActionCreator = sinon.stub(reduxFetchHelpers, 'fetchActionCreator');
fetchActionCreator.returns(expectedAction);
然后到测试体,用以下代码替换当前的存根代码:
--wwwroot
|_ src
|_app.html + app.js
|_home.html + home.js
|_mypage.html + mypage.js
我没有测试过这段代码,但它看起来应该有效。