【问题标题】:Jest: Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases开玩笑:无法窥探该属性,因为它不是函数;未定义给定而不是在执行我的测试用例时出错
【发布时间】:2020-09-04 03:59:48
【问题描述】:
           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: Cannot read property 'updateuser' of undefined:

*似乎 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 jestjs nestjs


    【解决方案1】:

    很可能,您的 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.spyOned 和模拟

    【讨论】:

    • 嗨,Jay,当我按照您的建议运行测试用例时。使用我的控制器类的相同方法“updateUser”显示错误消息“需要用户 ID”。
    • 您是否传入了一个带有id 属性的用户对象?我看到您正在传递一个 new UpsertUserDto(),但是在构造函数中是否创建了 id 属性和值?
    猜你喜欢
    • 2020-06-11
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2020-08-24
    • 2017-07-30
    • 2020-06-26
    相关资源
    最近更新 更多