【问题标题】:How to feed values in constructor in testcase in NestJs(jest)?如何在 NestJs(jest) 的测试用例中输入构造函数中的值?
【发布时间】:2022-10-20 12:03:14
【问题描述】:

我在我的项目中使用 NestJs 框架。在这里,我想为服务文件编写测试用例。但是我在服务文件中输入this.userPool 的值时遇到了问题。我收到userPoolIdclientId 未定义的错误。

我尝试了不同的解决方案,但没有什么对我有用。

服务.js

export class AuthService {
 private userPool: CognitoUserPool;
 constructor(private readonly authConfig: AuthConfig) {
   this.userPool = new CognitoUserPool({
     UserPoolId: this.authConfig.userPoolId,
     ClientId: this.authConfig.clientId,
   });
 }

authenticateUser(user: AuthCredentialsDto) {
   try {
     const { userName, password } = user;

     const authenticateDetails = new AuthenticationDetails({
       Username: userName,
       Password: password,
     });
     const userData = {
       Username: userName,
       Pool: this.userPool,
     };

     const newUser = new CognitoUser(userData);
     return new Promise((resolve, reject) => {
       ------------------------
   --------------------------------
     });
   } catch (error) {
     throw new BadRequestException(error.message);
   }
 }

服务规范.ts

import { AuthService } from './auth.service';
import {
  AuthenticationDetails,
  CognitoUser,
  CognitoUserAttribute,
  CognitoUserPool,
} from 'amazon-cognito-identity-js';
import { AuthConfig } from './cognito.service';

// const mockCognitoUserPool = () => ({
//   registerUser: jest.fn(),
// });

describe('AuthService', () => {
  let service: AuthService;
  let authConfig: AuthConfig;
  let userPool: CognitoUserPool;
  userPool = new CognitoUserPool({
    UserPoolId: authConfig.userPoolId,
    ClientId: authConfig.clientId,
  });
  // let userPool;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AuthService,
        AuthConfig,
        userPool
      ],
    }).compile();

    service = module.get<AuthService>(AuthService);
    authConfig = module.get<AuthConfig>(AuthConfig);
    // cognitoUserPool = module.get<CognitoUserPool>(CognitoUserPool);
  });

  describe('authenticateUser', () => {
    it('calls registerUser and returns the result', async () => {
      const mockUser = {
        userName: 'usernme',
        password: 'password',
      };

      // tasksRepository.findOne.mockResolvedValue(mockTask);
      const result = await service.authenticateUser(mockUser);
      expect(result).toEqual('result');
    });
  });

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

【问题讨论】:

    标签: node.js unit-testing jestjs nestjs testcase


    【解决方案1】:

    您的意思是在测试文件中拼写您的用户名属性“usernme”吗?

    【讨论】:

    • 它是我为模拟数据提供的样本值
    • 是的,我刚刚抓住了,对不起。这就是我在晚上 11 点尝试回答的结果
    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多