使用Jest进行JS脚本的单元测试:我可以模拟ES6类

时间:2018-12-12 09:56:22

标签: 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-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;
    }
    ...

1 个答案:

答案 0 :(得分:1)

已解决...使用以下规格:

 access_control:
    - { path: ^/(register|login)?$, roles: IS_AUTHENTICATED_ANONYMOUSLY}
    - { path: ^/?$, roles: ROLE_USER}