开玩笑:因为它不是函数,所以无法监视属性;未定义,但在执行我的测试用例时出现错误

问题描述 投票:0回答:1
           This is my controller class(usercontoller.ts) i am trying to write junit test cases for this class  

            import { UpsertUserDto } from '../shared/interfaces/dto/upsert-user.dto';
            import { UserDto } from '../shared/interfaces/dto/user.dto';
            import { UserService } from './user.service';
                async updateUser(@BodyToClass() user: UpsertUserDto): Promise<UpsertUserDto> {
                    try {
                        if (!user.id) {
                            throw new BadRequestException('User Id is Required');
                        }
                        return await this.userService.updateUser(user);
                    } catch (e) {
                        throw e;
                    }
                } 

这是我的TestClass(UserContollerspec.ts)在运行我的测试类时,出现错误“无法监视updateUser属性,因为它不是函数;而是未定义。遇到错误。但是,当我使用spyOn方法时,我不断收到TypeError:无法读取未定义的属性'updateuser':

*似乎jest.spyOn()在我做错的地方不能正常工作。有人可以帮我吗。我要通过的论点是?

    jest.mock('./user.service');

        describe('User Controller', () => {
            let usercontroller: UserController;
            let userservice: UserService;
            // let fireBaseAuthService: FireBaseAuthService;
            beforeEach(async () => {
                const module: TestingModule = await Test.createTestingModule({
                    controllers: [UserController],
                    providers: [UserService]
                }).compile();

                usercontroller = module.get<UserController>(UserController);

                userservice = module.get<UserService>(UserService);
            });

            afterEach(() => {
                jest.resetAllMocks();
            });

         describe('update user', () => {
             it('should return a user', async () => {
               //const result = new  UpsertUserDto();
               const testuser =  new  UpsertUserDto();
               const mockDevice = mock <Promise<UpsertUserDto>>();
               const mockNumberToSatisfyParameters = 0;
               //const userservice =new UserService();
               //let userservice: UserService;
                jest.spyOn(userservice, 'updateUser').mockImplementation(() => mockDevice);
              expect(await usercontroller.updateUser(testuser)).toBe(mockDevice);

          it('should throw internal  error if user not found', async (done) => {
            const expectedResult = undefined;
             ****jest.spyOn(userservice, 'updateUser').mockResolvedValue(expectedResult);****
             await usercontroller.updateUser(testuser)
              .then(() => done.fail('Client controller should return NotFoundException error of 404 but did not'))
              .catch((error) => {
                expect(error.status).toBe(503);
                expect(error.message).toMatchObject({error: 'Not Found', statusCode: 503});  done();
            });
        });
        });
        });
javascript node.js nestjs jest
1个回答
0
投票

[很有可能,您的UserService类还具有其他依赖关系,因此Nest无法实例化UserService类。当您尝试执行userService = module.get(UserService)时,您正在检索undefined,因此有关jest.spyOn()的错误。在单元测试中,您应该提供一个模拟提供程序来代替您的实际提供程序,如下所示:

describe("User Controller", () => {
  let usercontroller: UserController;
  let userservice: UserService;
  // let fireBaseAuthService: FireBaseAuthService;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            updateUser: jest.fn(),
            // other UserService methods
          }
        }
      ],
    }).compile();

    usercontroller = module.get<UserController>(UserController);

    userservice = module.get<UserService>(UserService);
  });
  // rest of tests
});

现在,当您检索UserService时,将具有一个具有适当功能的对象,然后可以对其进行jest.spyOn建模和模拟

© www.soinside.com 2019 - 2024. All rights reserved.