lundi 29 juin 2020

JEST - How to test function inside another function

I'm trying to test with Jest, but just check the entire method and not the functions inside it, I've tried it in many ways, nothing else works, how could I do to test the "compare" function from within the scope of the method?

Would I have to pass the compare as a parameter in the store method like that? "async store (req, res, compare)" ??

session.service.spec.ts

describe('SessionService', () => {
  let service: SessionService;
  let repo: Repository<User> 

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [      
        JwtModule.register({
          secret: jwtConstants.secret,
          signOptions: { expiresIn: '7d'}
        })
      ],
      providers: [
        JwtStrategy,
        SessionService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            findOne: jest.fn()
          }
        }
      ],
    }).compile();

    service = module.get<SessionService>(SessionService);
    repo = module.get<Repository<User>>(getRepositoryToken(User))
  });

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

  describe('Session', () => {    
    it('check if user has an account', async () => {
      const req = getMockReq({
        body: {
          email: 'email@gmail.com',
          password: '123456789'
        }
      })
      const { res } = getMockRes()

      await service.store(req, res)  

      const password = compare('123456789', req.body.password)

      expect(password).toBeTruthy()   
    })
    
    
  })
});

session.service.ts

 @Injectable()
export class SessionService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService
  ) {}


  async store(req: Request, res: Response): Promise<Response> {
    const { email, password } = req.body

    const user = await this.usersRepository.findOne({ where: { email }})    
    
    if(!user){
      return res.status(400).json({ error: 'Email inválido'})
    }

    const comparePassword = await compare(password, user.password)

    if(!comparePassword) {
      return res.status(400).json({ error: 'A senha está incorreta'})
    }    

    const payload = { 
      sub: user.id
    }

    return res.json({
      id: user.id,
      email,
      password,
      token: this.jwtService.sign(payload)
    })
  }
}

coverage: COVERAGE TEST IMAGE

Aucun commentaire:

Enregistrer un commentaire