Search code examples
reactjsreactjs-fluxfluxjestjs

How to test actions in Flux/React?


I'm trying to figure out how to test actions in flux. Stores are simple enough with the provided example, but there seems to be nothing out there for the actions/data/api layer.

In my particular app, I need to pre-process something before posting it to my server. Based on the advice in this post, I decided to implement the async stuff in my actions. What I can't figure out is how to test this preprocessing.

For example in MissionActions.js:

addMissionFromBank: function(bankMission) {
    var mission = new Mission({game: GameStore.getGame().resource_uri, order: Constants.MISSION_ORDER_BASE_INT}).convertBankMission(bankMission);
    var order = MissionSort.calcOrderBySortMethod(mission, MissionStore.getMissions(), GameStore.getGame().sort_method);
    mission['order'] = order;

    AppDataController.addMissionFromBank(mission);
}, 

In this function, I'm converting a stock mission (bankMission) into a regular mission and saving it to a game with the correct order key. Then I'm posting this new regular mission to my server, the callback of which is handled in my MissionStore.

Since this conversion code is important, I want to write a test for it but can't figure out how to do it since there seems to only be examples for testing stores and React components. Any suggestions?


Solution

  • Are you using the flux dispatcher or requiring AppDataController? Jest will automatically mock modules that you bring in via browserify's require. If you are importing AppDataController via require, then your test might look like this:

    jest.dontMock('MissionAction.js') // or path/to/MissionAction.js
    describe('#addMissionFromBank', function(){
      beforeEach(function(){
        MissionAction.addMissionFromBank(exampleMission);
      });
    
      it('calls AppDataController.addMissionFromBank', function(){
        expect(AppDataController.addMissionFromBank).toBeCalled());
      });
    });
    

    you want to call the non-mocked method that youre testing and check that the mock is called. to check if its been called at all use

    #toBeCalled()
    

    or if you want to check that its called with a specific value (for instance, check that its called with whatever mission evaluates to) use

    #toBeCalledWith(value)