2016-10-12 3 views
0

Ich habe eine Redux-Aktion, die einen asynchronen Aufruf an eine API hat.Stub eine Closure-Funktion mit Sinon für Redux-Aktionen

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)), 
     } 
    }) 
}

Ich versuche, die fetchActionCreator-Methode mit sinon Stubs zu verspotten. Dies ist meine Spec-Datei

 
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) 
    }) 

})

Aber irgendwie die Funktion verspottet wird nicht immer. Kannst du mir den richtigen Weg vorschlagen?

Antwort

2

Sie müssen die tatsächliche Funktion aus der Bibliothek, die aufgerufen wird, stumpf, nicht nur einen Stub erstellen, der den gleichen Namen hat.

Fügen Sie den folgenden auf Ihre Einfuhr in Ihren Tests:

import * as reduxFetchHelpers from 'redux-fetch-helpers'; 

Dann an den Körper Ihres Tests, ersetzen Sie die aktuellen Stubcode mit:

const fetchActionCreator = sinon.stub(reduxFetchHelpers, 'fetchActionCreator'); 
fetchActionCreator.returns(expectedAction); 

Ich habe diesen Code nicht getestet, aber Es sieht so aus als ob es funktionieren sollte.

Verwandte Themen