简体   繁体   English

对 Google Secret Manager 客户端的嘲讽被打破了

[英]jest mocking for Google Secret Manager client is broken

i am trying to getting the secrets from GCP Secret Manager as follow:我正在尝试从 GCP Secret Manager 获取秘密,如下所示:

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';

const getSecrets = async (storeId) => {
  try {
    const client = new SecretManagerServiceClient();
    const [accessReponse] = await client.accessSecretVersion({
      name: `projects/messaging-service-dev-b4f0/secrets/STORE_${storeId}_MESSANGER_CHANNEL_TOKEN/versions/latest`,
    });
    const responsePayload = accessReponse.payload.data.toString();
    return responsePayload;
  } catch (error) {
    console.error(`getSecretInfo: ${error.message}`);
    throw error;
  }
};

export default getSecrets;

for this function, to writing units i need to mock the SecretManagerServiceClient and it's function accessSecretVersion so following up the code i wrote for this.对于这个函数,为了编写单元,我需要模拟SecretManagerServiceClient和它的函数accessSecretVersion所以跟进我为此编写的代码。

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import { mocked } from 'ts-jest/utils';

import getSecrets from './../get-secrets';

jest.mock('@google-cloud/secret-manager');

const mockAccessSecretVersion = jest.fn().mockReturnValue({
    promise: jest.fn().mockResolvedValue({
        accessReponse: {
            payload: {
                data: 'secret'
            }
        }
    })
})

describe('getSecrets', () => {
    beforeEach(() => {
      jest.clearAllMocks();
      console.error = jest.fn();
    });
  
    it('should console log correct message if token exist on global', async () => {
        const mock = mocked(await (new SecretManagerServiceClient()).accessSecretVersion);
        mock.mockImplementationOnce(() => 'sa') 
        const factory = await getSecrets('1');
        jest.spyOn(global.console, 'error'); 
    });
  
  });
  

here, the test is broken as TypeError: (intermediate value) is not iterable , i am totally blocked here and any leads for this approach to resolve the mocking在这里,测试被破坏,因为TypeError: (intermediate value) is not iterable ,我在这里完全被阻止,并且这种方法解决模拟的任何线索

This error means you didn't mock the resolved value for the client.accessSecretVersion method correctly.此错误意味着您没有正确模拟client.accessSecretVersion方法的解析值。 Here is a complete unit testing solution:这是一个完整的单元测试解决方案:

get-secrets.ts : get-secrets.ts

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';

const getSecrets = async (storeId) => {
  try {
    const client = new SecretManagerServiceClient();
    const [accessReponse] = await client.accessSecretVersion({
      name: `projects/messaging-service-dev-b4f0/secrets/STORE_${storeId}_MESSANGER_CHANNEL_TOKEN/versions/latest`,
    });
    const responsePayload = accessReponse.payload!.data!.toString();
    return responsePayload;
  } catch (error) {
    console.error(`getSecretInfo: ${error.message}`);
    throw error;
  }
};

export default getSecrets;

get-secrets.test.ts : get-secrets.test.ts

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import getSecrets from './get-secrets';

const accessReponse = {
  payload: { data: { name: 'teresa teng' } },
};
const mClient = {
  accessSecretVersion: jest.fn(),
};

jest.mock('@google-cloud/secret-manager', () => {
  const mSecretManagerServiceClient = jest.fn(() => mClient);
  return { SecretManagerServiceClient: mSecretManagerServiceClient };
});

describe('getSecrets', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });
  afterAll(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
  });

  it('should console log correct message if token exist on global', async () => {
    mClient.accessSecretVersion.mockResolvedValueOnce([accessReponse]);
    const actual = await getSecrets('1');
    expect(actual).toEqual({ name: 'teresa teng' }.toString());
    expect(SecretManagerServiceClient).toBeCalledTimes(1);
    expect(mClient.accessSecretVersion).toBeCalledWith({
      name: `projects/messaging-service-dev-b4f0/secrets/STORE_1_MESSANGER_CHANNEL_TOKEN/versions/latest`,
    });
  });

  it('should log error and rethrow it', async () => {
    const errorLogSpy = jest.spyOn(console, 'error');
    const mError = new Error('network');
    mClient.accessSecretVersion.mockRejectedValueOnce(mError);
    await expect(getSecrets('1')).rejects.toThrowError('network');
    expect(SecretManagerServiceClient).toBeCalledTimes(1);
    expect(mClient.accessSecretVersion).toBeCalledWith({
      name: `projects/messaging-service-dev-b4f0/secrets/STORE_1_MESSANGER_CHANNEL_TOKEN/versions/latest`,
    });
    expect(errorLogSpy).toBeCalledWith('getSecretInfo: network');
  });
});

unit test result:单元测试结果:

 PASS  src/stackoverflow/64857093/get-secrets.test.ts (13.322s)
  getSecrets
    ✓ should console log correct message if token exist on global (6ms)
    ✓ should log error and rethrow it (9ms)

  console.error node_modules/jest-environment-jsdom/node_modules/jest-mock/build/index.js:866
    getSecretInfo: network

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |      100 |      100 |      100 |      100 |                   |
 get-secrets.ts |      100 |      100 |      100 |      100 |                   |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        14.744s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 开玩笑的测试问题,aws secret manager.then 方法 - Jest test issue, aws secret manager .then method 开玩笑 mocking 谷歌云/存储 typescript - Jest mocking google-cloud/storage typescript Google Secret Manager INVALID_ARGUMENT 错误 - Google Secret Manager INVALID_ARGUMENT Error GCP - 无法在 Cloud Run 中使用 Google Secret Manager (@google-cloud/secret-manager) - GCP - Can't use Google Secret Manager (@google-cloud/secret-manager) inside Cloud Run 如何将带有秘密管理器的谷歌应用引擎连接到 Postgres? - How to connect google app engine with secret manager to Postgres? 使用 Node.js 更新 Google Cloud Secret Manager 中的数据 - Update data in Google Cloud Secret Manager using Node.js 如何从谷歌秘密管理器访问多个秘密? - How to access multiple secrets from google secret manager? 从 Bitbucket 管道访问存储在 Google Secret Manager 中的环境变量 - Access environment variables stored in Google Secret Manager from Bitbucket pipelines Node.js - 在本地访问 Google Secret Manager - Node.js - Access Google Secret Manager locally 如何检查 Google Client_ID 和 Client_Secret 是否有效 - How to check if Google Client_ID and Client_Secret Valid or not
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM