Javascript 使用Jest对JS脚本进行单元测试:我可以模拟ES6类吗
当我从模块导入类时Javascript 使用Jest对JS脚本进行单元测试:我可以模拟ES6类吗,javascript,mocking,jestjs,es6-class,Javascript,Mocking,Jestjs,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-a
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--
这里是与我的问题相关的GoogleAuth库nodejs中最重要的编码
谷歌认证库节点JS模块
=======================================
/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/credentials.js
import {Credentials} from './credentials';
...
export abstract class AuthClient extends EventEmitter {
...
setCredentials(credentials: Credentials) {
this.credentials = credentials;
}
}
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" });
});
});
试图让它使用typescript和模拟返回/拒绝值。帮助…```从“谷歌认证库”导入{OAuth2Client};const mockedVerifyIdToken=jest.fn();它(“在垃圾令牌上返回404”,async()=>{OAuth2Client.prototype.verifyIdToken=mockedVerifyIdToken;mockedVerifyIdToken.MockedRejectedValueOnce(错误(“令牌中的段数错误”);const res=wait request(app).get(“/api/auth/google?code=12345679”);expect(res.status).toBe(404)```