Reputation: 46
I have been trying for a long time and nothing works, how could I test the "compare" function inside the "methodName" method?
teste.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { TesteService } from './teste.service';
describe('TesteService', () => {
let service: TesteService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TesteService],
}).compile();
service = module.get<TesteService>(TesteService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('methodName need return a string', () => {
expect(service.methodName()).toEqual(typeof String)
})
});
teste.ts
import { Injectable } from '@nestjs/common';
import { compare } from 'bcrypt'
@Injectable()
export class TesteService {
methodName() {
const password = '123456789'
const checkPassword = compare('123456789', password)
return checkPassword ? 'correct' : 'wrong'
}
}
if i do it this way would it be okay?
it('compare password', () => {
const checkPassword = compare('123456789', '123456789')
expect(checkPassword).toBeTruthy()
})
Upvotes: 0
Views: 755
Reputation: 199
As a principle in unit testing, we assume that external packages have been tested and are working. What you can do with your test, though, is to spy on the compare function and check weather your method is calling it and what it's calling with.
import * as bcrypt from 'bcrypt';
it('should call compare', () => {
const spyCompare = jest.spyOn(bcrypt, 'compare');
service.methodName();
expect(spyCompare).toHaveBeenCalled();
expect(spyCompare).toHaveBeenCalledWith('123456789');
})
Upvotes: 2