javascript - 开 Jest : Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases

标签 javascript node.js jestjs nestjs

           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();
            });
        });
        });
        });

最佳答案

您的 UserService 很有可能类具有其他依赖项,因此,Nest 无法实例化 UserService类(class)。当你试图做 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编辑和 mock

关于javascript - 开 Jest : Cannot spy the property because it is not a function; undefined given instead getting error while executing my test cases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61868153/

相关文章:

javascript - 在背景图像中使用正则表达式获取 div

javascript - 单元测试 Controller 使用 Jest、NodeJS

javascript - 无法访问本地 Node 服务器上创建的API

node.js - 使用 supertest 测试 Express NodeJS 端点

unit-testing - VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook

javascript - 为什么 AngularJS 会抛出错误的扩充错误

javascript - Handlebars 和 Javascript

node.js - Id 没有从嵌套数组中删除

javascript - 获取错误: invalid json response body at reason: Unexpected end of JSON input when using mockfetch with Jest

javascript - 错误 : request entity too large