[英]Unit Testing a JS script with Jest: Can I mock an ES6 class
當我從模塊導入類時
const { OAuth2Client } = require('google-auth-library');
我該如何嘲笑它?
jest.mock("google-auth-library"); // not mocking directly OAuth2Client
jest.mock("google-auth-library", OAuth2Client ) // is incorrect
如果我添加在線實施,則沒有類名
jest.mock("google-auth-library", () => {
return jest.fn().mockImplementation(() => {
return {
setCredentials: setCredentialsMock,
getAccessToken: getAccessTokenMock
}
})
});
所以我不能調用構造函數:
const oAuth2Client = new OAuth2Client({...});
歡迎反饋
更新1-
這是google-auth-library-nodejs中與我的問題相關的最重要的編碼
google-auth-library-nodejs模塊
====================================== /src/auth/index.ts ...從'./auth/oauth2client'導出{..,OAuth2Client,...}; ... const auth = new GoogleAuth(); 導出{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;
}
...
解決...使用以下規格:
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" });
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.