Categories
JavaScript Answers

How to mock React custom hook returned value with Jest?

To mock React custom hook returned value with Jest, we can call jest.mock.

For instance, we write:

jest.mock('module_name', () => ({
  useRect: () => [300, 200, jest.fn()]
}));

to call jest.mock with the module name and the function to mock the useRect hook with a function that returns the mocked values of the hook.

If we want to mock the hook once for a test, then use jest.spyOn with

import * as hooks from 'module_name';

it('a test', () => {
  jest.spyOn(hooks, 'useRect').mockImplementation(() => ([100, 200, jest.fn()]));
  // ...
});

to mock the useRect hook and return the mocked return values with mockImplementation.

We can just mock the return values since hooks are pure functions so they don’t commit side effects.

Categories
JavaScript Answers TypeScript Answers

How to set the data type of Axios mock using Jest TypeScript?

Sometimes, we want to set the data type of Axios mock using Jest TypeScript.

In this article, we’ll look at how to set the data type of Axios mock using Jest TypeScript.

How to set the data type of Axios mock using Jest TypeScript?

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.

For instance, we write

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

//...

mockedAxios.get.mockRejectedValue('error');
mockedAxios.get.mockResolvedValue({ data: {} });

to set the type of mockedAxios to jest.Mocked<typeof axios> with as.

We mock Axios with jest.mock('axios').

And then we can call mockedAxios.get.mockRejectedValue or mockedAxios.get.mockResolvedValue to set the mocked resolve or reject value of the promise returned by axios.get.

Conclusion

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.

Categories
JavaScript Answers TypeScript Answers

How to fix the “Cannot find name ‘it'” error in Jest TypeScript?

To fix the "Cannot find name ‘it’" error in Jest TypeScript, we need to install a few packages and change the test config.

First, we install the Jest TypeScript packages with

npm i npm install jest @types/jest ts-jest

Then in the jest.config.js file at the root folder, we add

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

so Jest can pick up test files and module files in the tests.

Then in tsconfig.json, we have

{
  "compilerOptions": {
    //...
    "types": ["reflect-metadata", "jest"],
    "typeRoots": ["./types", "./node_modules/@types"]
    //...
  },
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"]
}

so that the TypeScript compiler can pick up the TypeScript source code files in the folder by putting the include array.

And we exclude paths of non production source files with the exclude option.

We add 'jest' to types so that the type definitions of Jest is picked up by the TypeScript compiler.

Categories
JavaScript Answers

What’s the Jest equivalent to RSpec lazy evaluated variables (let)?

In this article, we’ll look at what’s the Jest equivalent to RSpec lazy evaluated variables (let).

What’s the Jest equivalent to RSpec lazy evaluated variables (let)?

The Jest equivalent to RSpec lazy evaluated variables (let) is defining a variable that’s shared between different tests.

For instance, we write

beforeEach(() => {
  let input = 'foo';
  beforeEach(() => {
    setupSomething(input);
  });

  describe('when input is bar', () => {
    beforeAll(() => {
      input = 'bar';
    });

    it('does something different', () => {

    });
  });

  describe('when input is baz', () => {
    beforeAll(() => {
      input = 'baz';
    });

    it('does something different', () => {

    });
  });
});

to define the input variable that’s available for all tests.

We assign values to input with different tests and use it in the setupSomething function for setting up each test.

Conclusion

The Jest equivalent to RSpec lazy evaluated variables (let) is defining a variable that’s shared between different tests.

Categories
JavaScript Answers

How to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest?

Sometimes, we want to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest.

In this article, we’ll look at how to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest.

How to fix the ‘jest.fn() value must be a mock function or spy’ error with Jest?

To fix the ‘jest.fn() value must be a mock function or spy’ error with Jest, we should add a spy to the function that we’re testing.

For instance, we write

const video = require('./video');

test('plays video', () => {
  const spy = jest.spyOn(video, 'play');
  const isPlaying = video.play();

  expect(spy).toHaveBeenCalled();
  expect(isPlaying).toBe(true);

  spy.mockRestore();
});

to call jest.spyOn to spy on the play function in the video module.

Then we call play to test the play method.

And then we check the behavior of the spy with toHaveBeenCalled and check the returned result with toBe.

Finally, we call mockRestore to reset the spy.

Conclusion

To fix the ‘jest.fn() value must be a mock function or spy’ error with Jest, we should add a spy to the function that we’re testing.