Have I accurately configured the unit test for my Nest.js project?

I've created a test for my Nest.js project. Can someone please review and confirm if this test is correct?

This test is focused on the nest service file. Here is the code:

tasks.service.ts

async getTaskById(id: string): Promise<Task> {
    const found = await this.taskModel.findById(id);

    if (!found) {
      throw new NotFoundException(`Task not found`);
    }

    return found;
 }

tasks.service.spec.ts

const mockTask = () => {
  return {
    _id: '613e4135ea46be481c2d88b2',
    name: 'Task 1',
    description: 'Go to school',
  };
};

const tasksServiceMock: Partial<TasksService> = {
  getTaskById: jest.fn().mockResolvedValue(mockTask()),
};

describe('TasksService', () => {
  let service: TasksService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        TasksService,
        {
          provide: TasksService,
          useValue: tasksServiceMock,
        },
      ],
    }).compile();

    service = module.get<TasksService>(TasksService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('getTaskById', () => {
    it('should retrieve task by ID', async () => {
      const task = await service.getTaskById(mockTask()._id);
      expect(task).toEqual(mockTask());
    });

    it('should throw Task Not Found error', async () => {
      tasksServiceMock.getTaskById = jest
        .fn()
        .mockRejectedValue(new NotFoundException('Task not found'));

      expect.assertions(2);

      try {
        await service.getTaskById('123456');
      } catch (e) {
        expect(e).toBeInstanceOf(NotFoundException);
        expect(e.message).toBe('Task not found');
      }
    });
  });
});

Answer №1

You have effectively discussed unit testing techniques. I would like to offer 2 suggestions regarding syntax:

  1. Consider defining mockTask directly as an object instead of using an arrow function for assignment.
  2. To handle error scenarios in test cases, opt for a cleaner syntax using async/await (https://jestjs.io/docs/asynchronous#asyncawait) over traditional try catch blocks.
it("should throw task Not found error", async () => {
  const mockError = new NotFoundException("Task not found");
  tasksServiceMock.getTaskById = jest.fn().mockRejectedValue(mockError);

  expect.assertions(2);

  await expect(service.getTaskById("123456")).rejects.toThrowError(mockError);
});

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 I efficiently display three items per click when tapping into jQuery data?

Here is the code that I have been working on: jQuery(document).ready(function( $ ) { var $container = $('#homegrid').masonry({ isAnimated: true, itemSelector: '.home-blocks', columnWidth: '.grid-sizer ...

Unlimited possibilities with parameters on an express server

I've set up React Router with recursive parameters, similar to the example here. On my Express server, I'm attempting to handle routes like /someRoute/:recursiveParameter? router.get('/someRoute/:recursiveParameter?', async (req, res ...

Exploring the Enum Type in GraphQL Apollo Query

Within the server environment, I have defined the enum and query in the schema: type Query { hello: String! getData(dataType: DataType!): [DataPoint] } enum DataType { ACCOUNT, USER, COMPANY } ... Now, on the client s ...

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

I am struggling to save a second variable that I received into my function

There is a function in my code that takes two values as input, both formatted like this: MyFunction("word1","word2") However, when the function receives the values, it looks like this: MyFunction(test1,test2){} The issue I'm facing is with storing ...

The error notification is not appearing in the correct location

I've been troubleshooting my jQuery error function for hours now (including the success function). I'm struggling to figure out how to display an error message only below the button that I click. To help clarify my issue, I've created a JSFi ...

Preventing double clicks in jQuery causing dysfunction in a PHP form function

Seeking assistance with a tricky jQuery bug that is causing issues on a specific feature of our CRM. The bug involves double form submissions, and we suspect it may be related to timing or order of operations. We have implemented a jQuery double click disa ...

Can TypeScript be implemented within nuxt serverMiddleware?

I recently began diving into the world of nuxtjs. When setting up, I opted to use typescript. Initially, everything was running smoothly until I decided to incorporate express in the serverMiddleware. Utilizing the require statement to import express funct ...

Calculate the total with the applied filters

My goal is to sum the data from the Number table after applying lookup filters. The current issue is that the sum remains fixed for all values and doesn't take into account the filter. Here's the JavaScript function I'm using to search and ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...

Rotate a sphere in three.js in order to align the mapped image of the globe with the GeoJSON data that is displayed in the same three

I have successfully implemented a globe in three.js with an image mapped onto the sphere. Furthermore, I am utilizing the ThreeGeoJSON library to visualize geojson data on top of the globe. However, the geographies from the geojson data do not align corr ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

Transform data from API arrays into a remapped object with updated keys and structure

I received the following output from my return object: { data: [ { ts: "20-10-26", events: 1500, }, { ts: "20-10-27", events: 1280, }, { ts: "20-10-28", events: 1111, } ] } T ...

Resetting radio buttons and select fields upon dynamically adding a new input field in ReactJS

I'm currently working on creating a stack of input fields, and I want to be able to dynamically add a new input field to the page. My approach involves storing default fields in an array state and using setArr() along with the spread operator to add a ...

Token Error in Angular App

I've encountered a sudden issue with my leaflet map. Every time I click on the map, a marker is added to the same coordinates despite my efforts to remove them using a function. Even though the markers-array is emptied, the markers remain visible on t ...

What is the correct way to chain custom callback functions using .queue()?

I am currently grappling with the concept of chaining custom functions: My code snippet looks like this: show_loader(0, function() { open_box($target_open, event.value, '.wide-col', function() { hide_loader(function() { ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Tallying and saving unique items along with their frequencies from an object array

Looking to efficiently count the number of unique elements and their occurrences in an array of objects. [ { name: 'Suman', game: '5A' }, { name: 'Suman', game: '5A' }, { name: 'Namus', ...

Converting JSON to JavaScript Date using UTC time

I am struggling with formatting the dates in a JSON object to work with highcharts. The JSON looks like this: [ [ "26-Sep-14", 10 ], [ "29-Sep-14", 75 ] ] Highcharts requires dates to be in the format Date. ...

Dimensions of Bootstrap carousel

I am attempting to create a Bootstrap carousel with full-width images (width: 100%) and a fixed height. However, when I set the width to 100%, the height automatically takes on the same value. I am unsure if the issue lies within my files. <div id="m ...