"Falta região em config" depois de tentar zombar SecretsManager com Brincadeira

0

Pergunta

Atualmente estou tentando zombar da AWS SecretsManager para o meu teste de unidade com tom de Brincadeira, e toda vez que eu estou a bater com o ConfigError Meu código é um pouco como este

//index.ts
import SM from "aws-sdk/clients/secretsmanager"
const secretManagerClient = new SM()
...
export const randomMethod = async (a: string, b: string) => {
  let secret
  const personalToken = {
    SecretId: process.env.secretId,
  }
  secretManagerClient
    .getSecretValue(personalToken, (err, data) => {
      if (err) {
        console.error(`[SECRETS MANAGER] Error fetching personal token : ${err}`)
      } else if (data && data.SecretString) {
        secret = data.SecretString
      }
    })
}

Meu mock vai como esta :

//index.test.js
const mockGetSecretValue = jest.fn((SecretId) => {
  switch (SecretId) {
    case process.env.GITHUB_PERSONAL_TOKEN:
      return {
        SecretString: process.env.GITHUB_PERSONAL_TOKEN_VALUE,
      }
    default:
      throw Error("secret not found")
  }
})

jest.mock("aws-sdk/clients/secretsmanager", () => {
  return jest.fn(() => {
    return {
      getSecretValue: jest.fn(({ SecretId }) => {
        return mockGetSecretValue(SecretId)
      }),
      promise: jest.fn(),
    }
  })
})

No entanto, recebo este erro atirado em mim : ConfigError: Missing region in config, o que eu entendo, em certa medida, no entanto, eu não entendo por que ocorre aqui no zombando parte...

Obrigado antecipadamente!

EDIT: Graças a 1ª resposta, eu consegui parar de ter esse erro. No entanto, o getSecretValue() o método é não devolver o valor de Segredo que eu quero.

aws-sdk jestjs mocking node.js
2021-11-15 16:00:57
2
0

Você NÃO deve usar o retorno de chamada de .getSecretValue() método com .promise() juntos. Basta escolher um deles. O erro significa que você não zombar do secretsmanager classe corretamente de aws-sdk.

E. g.

index.ts:

import SM from 'aws-sdk/clients/secretsmanager';
const secretManagerClient = new SM();

export const randomMethod = async () => {
  const personalToken = {
    SecretId: process.env.secretId || '',
  };
  try {
    const data = await secretManagerClient.getSecretValue(personalToken).promise();
    return data.SecretString;
  } catch (err) {
    console.error(`[SECRETS MANAGER] Error fetching personal token : ${err}`);
  }
};

index.test.ts:

import { randomMethod } from '.';
import SM from 'aws-sdk/clients/secretsmanager';
import { mocked } from 'ts-jest/utils';
import { PromiseResult } from 'aws-sdk/lib/request';

jest.mock('aws-sdk/clients/secretsmanager', () => {
  const mSecretManagerClient = {
    getSecretValue: jest.fn().mockReturnThis(),
    promise: jest.fn(),
  };
  return jest.fn(() => mSecretManagerClient);
});

describe('69977310', () => {
  test('should get secret value', async () => {
    process.env.secretId = 's1';
    const mSecretManagerClient = mocked<InstanceType<typeof SM>>(new SM());
    const mGetSecretValueRequest = mocked(mSecretManagerClient.getSecretValue());

    mGetSecretValueRequest.promise.mockResolvedValue({
      SecretString: JSON.stringify({ password: '123456' }),
    } as PromiseResult<any, any>);
    const actual = await randomMethod();
    expect(actual).toEqual(JSON.stringify({ password: '123456' }));
    expect(mSecretManagerClient.getSecretValue as jest.Mocked<any>).toBeCalledWith({ SecretId: 's1' });
  });

  test('should throw error', async () => {
    process.env.secretId = 's1';
    const logSpy = jest.spyOn(console, 'error').mockImplementation(() => 'suppress error log for testing');
    const mSecretManagerClient = mocked<InstanceType<typeof SM>>(new SM());
    const mGetSecretValueRequest = mocked(mSecretManagerClient.getSecretValue());

    const mError = new Error('network');
    mGetSecretValueRequest.promise.mockRejectedValue(mError);
    await randomMethod();
    expect(logSpy).toBeCalledWith(`[SECRETS MANAGER] Error fetching personal token : ${mError}`);
    expect(mSecretManagerClient.getSecretValue as jest.Mocked<any>).toBeCalledWith({ SecretId: 's1' });
  });
});

resultado do teste:

 PASS  examples/69977310/index.test.ts (7.722 s)
  69977310
    ✓ should get secret value (4 ms)
    ✓ should throw error (1 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |       50 |     100 |     100 |                   
 index.ts |     100 |       50 |     100 |     100 | 6                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.282 s, estimated 10 s

versões do pacote:

"aws-sdk": "^2.875.0",
"typescript": "^4.1.2",
"jest": "^26.6.3",
2021-11-16 09:29:00

Obrigado pela sua resposta, e você está certo, eu li errado o AWS SDK documentação. No entanto, eu estou lutando para fazer este trabalho. Para mais contexto, neste momento estou a testar a unidade de um lambda que usa o randomMethod()e eu estou tentando link que o método para esse escarnecido SecretsManager instância, e apesar de não ter a configuração de erro de mais, o getSecretValue() não devolver o segredo que eu quero. Eu atualizei o código acima.
Fares
0

Eu tenho negligenciado o fato de que eu estava usando uma chamada de retorno para ignorar a promise().

O seguinte é o código correto:

const mockGetSecretValue = jest.fn((SecretId, callback) => {
  console.log("secretId", SecretId)
  switch (SecretId) {
    case process.env.GITHUB_PERSONAL_TOKEN:
      const data = {
        SecretString: process.env.GITHUB_PERSONAL_TOKEN_VALUE,
      }
      callback(null, data)
      break;
    default:
      const err = new Error("secret not found")
      throw err
  }
})

jest.mock("aws-sdk/clients/secretsmanager", () => {
  return jest.fn(() => {
    return {
      promise: jest.fn(),
      getSecretValue: jest.fn(({ SecretId }, callback) => {
        return mockGetSecretValue(SecretId, callback)
      }),
    }
  })
})

Obrigado novamente por sua ajuda @slideshowp2!

2021-11-16 14:24:07

Em outros idiomas

Esta página está em outros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................