There are lots of different ways to mock things out using Jest. I have a whole article on mocking out useSelector and useDispatch.

In this post, I’m going to describe a few more ways you can mock things out according to your needs.

  1. Mocking out a return value for your entire test suite

If your entire test suite needs the same mocked implementation for all tests, it might be cleanest to mock out the function at the top of the spec file.

// Top of your spec file

jest.mock('react-redux', () => ({
useSelector: jest.fn().mockResolvedValue(Y'),
}))

2. Mocking out a named export in your own codebase

// Top of your spec file
import { foo } from '../utils/foo'
jest.mock('../utils/foo')// You can either mock an implementation for your entire test suite, or do this for each test case
foo.mockImplementation(() => {/* dummy implementation */})

Don’t use — you need !

.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

Just want to leave a link to the post I’ve written over on the Voliyo website!


Although the AAA method of structuring tests originally comes from the C# world, I’ve incorporated it into the way I write JS/TS tests, as I think it truly makes things more readable.

The basic principle is this; split your tests into blocks separated by , , comments.

Example:

// ARRANGE
const input1 = 1
const input2 = 1
const expectedOutput = 2
// ACT
const actualOutput = add(input1, input2)
// ASSERT
expect(expectedOutput).toEqual(actualOutput)

When I gloss over the above example, my eyes are immediately drawn to the and blocks, and when debugging, this makes it easy to understand where I should start my efforts.

Try it out for yourself!


Naturally, you might want to test components that are connected to a Redux store. Mocking is a simple way to go about injecting a Redux state into your components and creating deterministic tests.

Step 1: import in your test file:

import * as reactRedux from 'react-redux'

Step 2: spy on and :

describe('test suite', () => {
const useSelectorMock = jest.spyOn(reactRedux, 'useSelector')
const useDispatchMock = jest.spyOn(reactRedux, 'useDispatch')
...
})

Step 3: make sure the mocks are cleared before each test case:

beforeEach(() => {
useSelectorMock.mockClear()
useDispatchMock.mockClear()
})

Usage

Mocking out state

it('does something', () => {
// ARRANGE
useSelectorMock.mockReturnValue({/* State goes here */})

... …


You might argue that you shouldn’t place high-level components that rely on Redux into Storybook. Sometimes, however, it isn’t as easy as that.

The main problem that I’ve run in to is dispatching an initial state from doesn’t work from within stories. Worse still, if I create a wrapper component inside a file, this wrapper component is picked up as a story itself.

The Solution

Create a separate file called . …


One beauty of Redux is how extendable it is. You can easily create your own logging middleware, or middleware that pumps data into your analytics systems. I briefly want to outline the simple steps you need to take to get started.

Step 1: Create your middleware

import { Dispatch, Middleware, MiddlewareAPI } from 'redux'export const myLoggingMiddleware = (_: MiddlewareAPI) => (next: Dispatch) => (action: any) => {
// Here you have access to `action.type` and `action.payload`
console.log('Logging action with type', action.type)

// You should always do this at the end of your middleware
return next(action)
}

Step 2: Hook this up to your…


There are cases where you want to prevent browsers from caching certain pages you serve.

Here are a few HTTP Headers that I’ve found have worked a treat:

Cache-Control 'no-store';
Cache-Control 'no-cache';
Expires 0;

More info on how these work can be found here and here.


Do your styled component classnames keep changing when you run snapshot tests?

Not to worry. There’s a little library that’ll help you with that.

Install and add it to your file:

...import 'jest-styled-components'...

This should stabilise the styled component classnames (make them ‘deterministic’) so that you can run your test suite repeatedly, hassle free.


Test configuration can often be the biggest barrier when coming to write tests. I’d like to share a quick snippet that I use when testing React Hooks that rely on a Redux state.

First, install , as this is the helper library we’ll use to test hooks.

Next, in your test file:

import { combineReducers, createStore } from 'redux'const store = createStore(combineReducers({ /* Add reducers that your hook needs */}))

You can alternatively use if you’re using Redux Toolkit, but the main thing here is to set up a store which creates the state your hooks need.

Create a basic Wrapper…

About

Tom Szpytman

Full-stack + Product. Available for hire either as an independent contractor, or as part of a voliyo.dev team. Inquiries: mail [at] voliyo.dev.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store