Skip to content

Instantly share code, notes, and snippets.

@roblafeve
Last active March 27, 2017 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roblafeve/e680664e88fb635136c0d05740ce9862 to your computer and use it in GitHub Desktop.
Save roblafeve/e680664e88fb635136c0d05740ce9862 to your computer and use it in GitHub Desktop.

Actions

Actions correspond to Redux Async Action Creators and are responsible for dispatching store actions (found:'../src/store') or other async actions.

Typical Structure

While the specific implementation may vary, async actions take this basic form. Partial application is used to provide easy dependency injection (useful for easy testing of success and failure cases).

index.js

// ./someAction/index.js
import { someRequestPost } from "config/requests/someRequest";
import someStore from "store/someStore";
import otherStore from "store/otherStore";

export const action = ({ request }) =>
  form =>
    dispatch =>
      request({ body: form })
        .then(response => {
          dispatch(someStore.set(response));
        })
        .catch(error => {
          dispatch(otherStore.set(error));
        });

// Export default with dependencies injected
export default action({ request: someRequestPost });

test.js

Goal of test is to assert that specific actions were dispatched using redux-mock-store.

// ./someAction/test.js
import { action } from "."; // Import member, not default export so we can inject request
import mockStore from "utils/mockStore";
import someStore from "store/someStore";
import otherStore from "store/otherStore";

// Instantiate mock redux store
const store = mockStore({});

// Inject success and failure requests
const actionSuccess = action({
  request: () => Promise.resolve({ name: "Tim" }),
});
const actionFailure = action({
  request: () => Promise.reject("Bad request"),
});

describe("actionPost", () => {
  afterEach(() => store.clearActions());

  it("success actions are dispatched", () => {
    return store.dispatch(actionSuccess()).then(() => {
      const actual = store.getActions();
      const wanted = [someStore.set({ name: "Tim" })];
      expect(actual).toEqual(wanted);
    });
  });

  it("failure actions are dispatched", () => {
    return store.dispatch(actionFailure()).then(() => {
      const actual = store.getActions();
      const wanted = [otherStore.set("Bad request")];
      expect(actual).toEqual(wanted);
    });
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment