Nestjs Testing in signup BadRequestException: email in use error

561 Views Asked by At

user.service.ts

async findWithMail(email:string):Promise<any> {
    return this.userRepository.findOne({email});
  }

auth.service.ts

async signup(email:string,password:string,name?:string,surname?:string,phone:string){
    if(email) {
      const users = await this.userService.findWithMail(email);
      if(users) {
        throw new BadRequestException('email in use');
      }
    }
    if(!password) return {error:"password must be!"};
    const salt = randomBytes(8).toString('hex');
    const hash = (await scrypt(password,salt,32)) as Buffer;
    const result = salt + '.' +hash.toString('hex');
    password = result;
    const user = await 
    this.userService.create(email,password,name,surname,phone);
    return user;
}

auth.service.spec.ts

let service:AuthService;
let fakeUsersService: Partial<UserService>;

describe('Auth Service',()=>{

  beforeEach(async() => {
    fakeUsersService = {
      findWithMail:() => Promise.resolve([]),
      create:(email:string,password:string) => Promise.resolve({email,password} as User),
    }
  
    const module = await Test.createTestingModule({
      providers:[AuthService,{
        provide:UserService,
        useValue:fakeUsersService
      }],
    }).compile();
    service = module.get(AuthService);
  });
  
  
  it('can create an instance of auth service',async()=> {
    expect(service).toBeDefined();
  })
  it('throws an error if user signs up with email that is in use', async () => {
      await service.signup('[email protected]', 'asdf')
  });
})

When ı try to run my test its give me error even this email is not in database its give error: BadRequestException: email in use. I couldnt figure out how to solve problem

2

There are 2 best solutions below

0
Liar Рonest On

You can use isExists method instead of findOne.

Also you can add extra check for your findWithMail method. Check the length of db request result. Like if (dbReqResult.length === 0) return false; else true

0
Rodericus Ifo Krista On

please put your attention on your mocked user service, especially on findWithEmail function, this part

beforeEach(async() => {
 fakeUsersService = {
  findWithMail:() => Promise.resolve([]),
  create:(email:string,password:string) => 
  Promise.resolve({email,password} as User),
 }
 ...

try to resolve the promise to be null not [] (empty array) or change your if(users) on your auth.service to be if(users.length > 0), why? it because empty array means to be thruthy value so when run through this process on your auth.service

if(email) {
  const users = await this.userService.findWithMail(email);
  // on this part below
  if(users) {
    throw new BadRequestException('email in use');
  }
}

the 'users' executed to be truthy value so it will invoke the error. I hope my explanation will help you, thank you