npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jest-redux-thunk

v1.1.1

Published

Custom jest matchers to help with testing redux thunk actions

Downloads

76

Readme

jest-redux-thunk

Custom jest matchers to help with testing redux thunk actions

The problem

Your redux actions leverage redux-thunk and you want to test them. There are many ways to perform testing on redux actions, but to keep it simple, I tend to just use jest mock functions. However, testing dispatch function as a thunk in this way involves digging into mock.calls properties and results in a bunch of boilerplate in order to make certain assertions.

This solution

jest-redux-thunk provides a set of custom jest matchers that are specific to testing redux-thunk actions using the mock function approach. This includes looking for the type property on action objects and outputting helpful test failure messages.

Installation

This module is distributed via npm and should be installed as a devDependencies:

npm install --save-dev jest-redux-thunk

Usage

Import jest-redux-thunk which loads this library's matchers. You can perform this import in each test file or once in a jest setup file (recommended)

Custom matchers

toBeDispatchedWithActionType

Assert that an action has been dispatched with a certain type.

import `jest-redux-thunk`

it('dispatches action with type CREATE_STORY', () => {
  const dispatchMock = jest.fn()

  someThunkActionCreator(dispatchMock)

  expect(dispatchMock).toBeDispatchedWithActionType('CREATE_STORY')
})

This matcher passes if there is at least one action dispatched that has a type that matches the expected type.

toBeDispatchedWithActionTypeOrder

Assert that actions are dispatched in a certain order.

import `jest-redux-thunk`

it('dispatches story load actions in correct order', () => {
  const dispatchMock = jest.fn()

  someThunkActionThatDispatchesMultipleTimes(dispatchMock)

  expect(dispatchMock).toBeDispatchedWithActionTypeOrder(['LOAD_STORY', 'LOAD_AUTHORS', 'LOAD_CHARACTERS'])
})

This matcher will fail if the order in which actions are dispatched doesn't match expected order or if expected action(s) was not dispatched at all.

toBeDispatchedWithAction

Asserts that an action and its data match what is dispatched. This is similar to toMatchObject where the subset comparison is performed on each key of the action (e.g. payload, meta, etc)

import `jest-redux-thunk`

it('dispatches LOAD_STORY action', () => {
  const dispatchMock = jest.fn()

  dispatchMock ({
    type: 'LOAD_STORY',
    payload: {
      items: ['book1', 'book2', 'book3']
    },
    meta: {
     isLoading: false
    }
  })

  expect(dispatchMock).toBeDispatchedWithAction({
    type: 'LOAD_STORY',
    // this payload object is a subset of the payload object above
    payload: {
      items: ['book1', 'book2', 'book3']
    }
  })
})

This matcher will fail if:

  • no action is dispatched
  • multiple actions with the same expected action.type are dispatched
  • the action dispatched does not match the expected action (using similar logic to toMatchObject)

FAQ (actually, just one question that some might have regarding these matchers)

Why not just use toHaveBeenCalledWith?

Good question! toHaveBeenCalledWith uses a deep equal comparison to compare expected parameters and actual. For testing redux thunk, that might be too strict and lead to bloated tests

it("action dispatches CREATE_STORY action", () => {
  const dispatchMock = jest.fn();

  dispatchMock({
    type: "CREATE_STORY",
    payload: {
      story: {
        id: 1,
        title: "New Story"
      }
    }
  });

  // fails!
  expect(dispatchMock).toHaveBeenCalledWith({
    type: "CREATE_STORY"
    // exclude payload in assertion as that's part of another test
  });
});

The above test would fail because we didn't specify payload in the value passed to toHaveBeenCalledWith.

This library's extensions allow for testing dispatch functions based on action types that have been dispatched:

it("action dispatches CREATE_STORY action", () => {
  const dispatchMock = jest.fn();

  dispatchMock({
    type: "CREATE_STORY",
    payload: {
      story: {
        id: 1,
        title: "New Story"
      }
    }
  });

  // passes!
  expect(dispatchMock).toBeDispatchedWithActionType("CREATE_STORY");
});