JEST-如何在另一个函数中测试函数

时间:2020-06-29 18:13:27

标签: node.js unit-testing testing jestjs

我正在尝试使用Jest进行测试,但是只检查了整个方法而不是其中的函数,我已经尝试了很多方法,没有其他办法,我该怎么做才能从中测试“比较”函数在方法范围内?

我是否必须像这样在store方法中将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 TEST IMAGE

0 个答案:

没有答案