Reputation:
when I import a class from a module
const { OAuth2Client } = require('google-auth-library');
How can I mock it ?
jest.mock("google-auth-library"); // not mocking directly OAuth2Client
jest.mock("google-auth-library", OAuth2Client ) // is incorrect
And if I add the online implementation, I don't have the class name
jest.mock("google-auth-library", () => {
return jest.fn().mockImplementation(() => {
return {
setCredentials: setCredentialsMock,
getAccessToken: getAccessTokenMock
}
})
});
so I cannot call the constructor :
const oAuth2Client = new OAuth2Client({...});
Feedback welcome
UPDATE 1 --
Here as the most important coding from google-auth-library-nodejs related to my issue
google-auth-library-nodejs module
======================================= /src/auth/index.ts ... export {.., OAuth2Client,...} from './auth/oauth2client'; ... const auth = new GoogleAuth(); export {auth, GoogleAuth};
=======================================
/src/auth/oauth2client.js
import {AuthClient} from './authclient';
...
export class OAuth2Client extends AuthClient {
....
constructor(clientId?: string, clientSecret?: string, redirectUri?: string);
constructor(
...
super();
...
this._clientId = opts.clientId;
this._clientSecret = opts.clientSecret;
this.redirectUri = opts.redirectUri;
...
}
...
getAccessToken(): Promise<GetAccessTokenResponse>;
...
}
======================================= /src/auth/authclient.ts
import {Credentials} from './credentials';
...
export abstract class AuthClient extends EventEmitter {
...
setCredentials(credentials: Credentials) {
this.credentials = credentials;
}
}
======================================= /src/auth/credentials.js
export interface Credentials {
refresh_token?: string|null;
expiry_date?: number|null;
access_token?: string|null;
token_type?: string|null;
id_token?: string|null;
}
...
Upvotes: 1
Views: 2972
Reputation: 1
Didn't work for me.
This worked for me.
jest.mock('google-auth-library', () => {
return {
OAuth2Client: jest.fn(() => ({
verifyIdToken: jest.fn((variable) => Promise.resolve({
getPayload: jest.fn().mockReturnValue({
email: '[email protected]'
})
}))
}))
};
});
Upvotes: 0
Reputation:
SOLVED ... using the following specs :
jest.mock("google-auth-library");
const { OAuth2Client } = require('google-auth-library');
const setCredentialsMock = jest.fn();
const getAccessTokenMock = jest.fn();
OAuth2Client.mockImplementation(() => {
return {
setCredentials: setCredentialsMock,
getAccessToken: getAccessTokenMock
}
});
import index from "../index.js"
describe('testing...', () => {
it("should setCredentials correctly....", () => {
// GIVEN
const oAuth2Client = new OAuth2Client("clientId", "clientSecret", "redirectUri");
// WHEN
oAuth2Client.setCredentials({ refresh_token: "aRefreshToken"});
// THEN
expect(setCredentialsMock).toHaveBeenCalledWith({ refresh_token: "aRefreshToken" });
});
});
Upvotes: 3