A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service:

// UserService.ts

export const create = async body => {
  ... save data to database ...
}

export const getById = async id => {
  ... retrieve user from database ...
}

The testing code is as follows:

// auth.test.ts

import * as UserService from '../services/UserService';

jest.mock('../services/UserService');

describe('Authorization', () => {
  beforeAll(() => {
    UserService.getById = jest.fn();
  });
});

However, an error occurred:

Cannot assign to 'getById' because it is a read-only property.

Answer №1

Below is the solution:

UserManagementService.ts:

export const createUser = async body => {
  console.log("... saving user to database ...");
};

export const getUserById = async id => {
  console.log("... fetching user from the database ...");
};

authentication.ts:

import * as UserManagementService from "./UserManagementService";

export async function authenticate(userService: typeof UserManagementService) {
  await userService.getUserById("1");
  await userService.createUser({ name: "test" });
}

authentication.test.ts:

import * as UserManagementService from "./UserManagementService";
import { authenticate } from "./authentication";

jest.mock("./UserManagementService", () => {
  const mockUserService = {
    getById: jest.fn(),
    create: jest.fn()
  };
  return mockUserService;
});

describe("UserManagementService", () => {
  it("should authenticate successfully", async () => {
    await authenticate(UserManagementService);
    expect(UserManagementService.getById).toBeCalledWith("1");
    expect(UserManagementService.create).toBeCalledWith({ name: "test" });
  });
});

Unit test results with complete coverage:

 PASS  src/stackoverflow/59035729/authentication.test.ts (13.16s)
  UserManagementService
    ✓ should authenticate successfully (8ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 auth.ts  |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.499s

Source code available at: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59035729

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can different styles be seamlessly combined when customizing Fabric components?

Imagine I am enhancing a Fabric component by adding custom styles and wishing to combine any additional styles passed in through its props. Here's the solution I've devised: const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fab ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

Could it be possible for TypeScript inference to directly infer the value and omit the key in the process?

class A { state: B } class B { something: C } class C { a: string; b: boolean; } type MagicType = ... const c: MagicType<A> c.state.a = "123" c.state.b = true; Is it possible to achieve the mentioned functionality without altering the exi ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application. I have a parent component that loads some data: In admin-area.component.ts: ngOnInit(): void { forkJo ...

How can Jest be configured to test for the "permission denied" error?

In my Jest test, I am testing the behavior when trying to start a node http server with an invalid path for the socket file: describe('On any platform', (): void => { it('throws an error when trying to start with an invalid socket P ...

How to create classes in typescript without utilizing the class keyword

As someone new to TypeScript, I have a curious question about classes. In pre-ES6 JavaScript, there were no classes. So, naturally, one would think it's possible to avoid using them in TypeScript as well. However, I am struggling to figure out the c ...

What is the process for creating documentation for a TypeScript enum type with the format of { [key]: value }

I am currently developing a logger service for nodeJS using Typescript. One important component of this project is an enum that looks like this: enum LOG_TYPES { NONE = 0, ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4, } Along with the enum, I have i ...

Guide on inserting tooltip to designated header column in primeNG data table

Html <p-table #dt1 [columns]="cols" [value]="cars1"> <ng-template pTemplate="header" let-columns> <tr> <th *ngFor="let col of columns"> {{col.header}} </th> ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

shallow rendering does not recognize this.props as a function

I'm currently facing an issue while trying to test my (legacy) component using jest/enzyme. Here is a snippet of the component: export default class MyComponent extends Component { constructor( props ) { super( props ); this.handl ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

Encountering difficulty importing a module from a different module within Nuxt

Within my Nuxt project directory, there exists a specific folder named modules which houses my customized modules. For this illustration, it includes the modules foo and bar. The inclusion of foo in the nuxt.config.js file appears as follows: // nuxt.confi ...

A guide on simulating x-date-pickers from mui using jest

I have successfully integrated a DateTimePicker into my application, but I am facing an issue with mocking it in my Jest tests. Whenever I try to mock the picker, I encounter the following error: Test suite failed to run TypeError: (0 , _material.gen ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...