Search code examples
node.jsjestjsnestjsjest-fetch-mock

How do I initialized while write junit testcase on nodejs (JavaScript) decorators ? my costume decorator (body to class) is not find


import { BodyToClass } from 'src/shared/decorators/body';
import { UserService } from './user.service';

@Put()
    async updateUser(@BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {`enter code here`
        try {
            if (!user.id) {
                throw new BadRequestException('User Id is Required');
            }
            return await this.userService.updateUser(user);
        } catch (e) {
            throw e;
        }
    }`

How do I initialized while write junit testcase on nodejs (JavaScript) decorators ? my costume decorator (body to class) is not find.

import { BodyToClass } from 'src/shared/decorators/body';
import { Test, TestingModule } from '@nestjs/testing';
import { UserDto } from 'src/shared/interfaces/dto/user.dto';
import { UserController } from './user.controller';
import { UserService } from './user.service';


jest.mock('./user.service');
// jest.mock('src/shared/decorators/body');

describe('App Controller', () => {
    let testingModule: TestingModule;
    let controller: UserController;
    let service: UserService;
beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,

          useFactory: () => ({
            getUserById: jest.fn(() => true),
          }),
        },

            // provide: 'BodyToClass',
            // useClass:BodyToClass
      ],
    }).compile();
    controller = testingModule.get(UserController);
    service = testingModule.get(UserService);
  });
  describe('update user', () => {
    it('it should update the users', async () => {
      expect(service.updateUser).toHaveReturned();
    });
  });

 });

When I try to execute this Testclass(UserController.spec.ts Node.js I get the following error

import { BodyToClass } from 'src/shared/decorators/body' can not find module,although i have import the package, so

So, my questions are:

1:how we mock decorator while write the testcases. 2:do we need to initialized or mock "@BodyToClass()" ? 3: where i am doing mistake ?


Solution

  • Don't import from src. You should be using a relative import instead, where you do something similar to

    import { BodyToClass } from '../shared/decorators/body';
    

    to ensure that when the code gets compiled (moved to JS in the dist) you are no longer requiring the src directory to exist