I am currently doing unit test for the services in Nestjs using Jest, one of which is using the google Oauth service. My goal is to verify the token from google and get the email to continue the process. Are there any ways to mock or skip the auth process and return the mocked email? Here is my code:
// ...other modules
import { google, Auth } from "googleapis";
export class GoogleAuthService {
oauthClient: Auth.OAuth2Client;
constructor(
// ...some provider services
) {
const clientID = this.configService.get("GOOGLE_AUTH_CLIENT_ID");
const clientSecret = this.configService.get("GOOGLE_AUTH_CLIENT_SECRET");
// how can I mock this?
this.oauthClient = new google.auth.OAuth2(clientID, clientSecret);
}
async authenticate(token: string) {
try {
// or need to mock this?
const tokenInfo = await this.oauthClient.getTokenInfo(token);
const email = tokenInfo.email;
// ...other code
} catch (error) {
throw new UnauthorizedException();
}
}
}
describle("AuthService unit test", () => {
let authService: AuthService;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
GoogleAuthService,
// ... other services
],
}).compile();
GoogleAuthService = await module.get(GoogleAuthService);
});
describe("google login", () => {
it("should return a user", async () => {
// don't know how to test the 'authenticate' service
const mockedToken = "mockedToken";
const result = await GoogleAuthService.authenticate(mockedToken);
expect(typeof result).toEqual(User);
});
});
})
Thanks for the help!!!