Jest.js 又用承诺来嘲弄

l5tcr1uw  于 2022-12-25  发布在  Jest
关注(0)|答案(2)|浏览(170)

我读了Jest Mock Promise with Params,基本上有相同的代码片段,但它一直向我抛出错误“ParameterNotFound”
// --测试代码--

it("get parameter", async done => {
    const paramsForGetParam = {
      Name: "StripeSecretKey",
      WithDecryption: true
    };

    const mockedResponseData = {
      Parameter: {
        Name: "StripeSecretKey",
        Type: "SecureString",
        Value: "myVal",
        Version: 1,
        LastModifiedDate: 1530018761.888,
        ARN: "arn:aws:ssm:us-east-1:123456789012:parameter/helloSecureWorld"
      }
    };

    // ssm.getParameter().promise = jest.fn();
    ssm.getParameter = jest.fn();
    ssm.getParameter.mockImplementation(() => ({
      promise: jest
        .fn()
        .mockImplementation(() => Promise.resolve(mockedResponseData))
    }));
    ssm
      .getParameter()
      .promise.mockImplementation(() => Promise.resolve(mockedResponseData));

    const data = await helpers.getSsmVar("StripeSecretKey");
    expect(data).toEqual(mockedResponseData.Parameter.Value);
    expect(ssm.getParameter).toHaveBeenCalledTimes(1);
    done();
  });

下面是我的开发代码:

const aws = require("aws-sdk");
aws.config.update({ region: "us-east-1" });
const ssm = new aws.SSM();
const baseSsm = `/mybox/`;

module.exports = {
  getSsmVar: async function(name) {
    var params = {
      Name: baseSsm + name,
      WithDecryption: true
    };
    var request = await ssm.getParameter(params).promise();
    return request;
  }
};

但是它一直失败,下面没有告诉我哪个参数不是found.aws说要检查name参数,但我认为name(params.Name)是正确的?

● Helpers Tests › get parameter

    ParameterNotFound: 

      at Request.extractError (node_modules/aws-sdk/lib/protocol/json.js:50:27)
      at Request.callListeners (node_modules/aws-sdk/lib/sequential_executor.js:112:20)
      at Request.emit (node_modules/aws-sdk/lib/sequential_executor.js:77:10)
      at Request.emit (node_modules/aws-sdk/lib/request.js:713:14)
      at Request.transition (node_modules/aws-sdk/lib/request.js:25:10)
a64a0gku

a64a0gku1#

下面是解决方案,您可以手动使用jest.mock()模拟aws-sdk
index.js

const aws = require('aws-sdk');
aws.config.update({ region: 'us-east-1' });
const ssm = new aws.SSM();
const baseSsm = `/mybox/`;

module.exports = {
  async getSsmVar(name) {
    const params = {
      Name: baseSsm + name,
      WithDecryption: true
    };
    const request = await ssm.getParameter(params).promise();
    return request;
  }
};

index.spec.js

jest.mock('aws-sdk', () => {
  const mockedSSM = {
    getParameter: jest.fn().mockReturnThis(),
    promise: jest.fn()
  };
  const mockedConfig = {
    update: jest.fn()
  };
  return {
    SSM: jest.fn(() => mockedSSM),
    config: mockedConfig
  };
});

const helpers = require('.');
const aws = require('aws-sdk');
const ssm = new aws.SSM();

describe('helpers', () => {
  it('get parameter', async () => {
    const mockedResponseData = {
      Parameter: {
        Name: 'StripeSecretKey',
        Type: 'SecureString',
        Value: 'myVal',
        Version: 1,
        LastModifiedDate: 1530018761.888,
        ARN: 'arn:aws:ssm:us-east-1:123456789012:parameter/helloSecureWorld'
      }
    };

    ssm.getParameter().promise.mockResolvedValueOnce(mockedResponseData);
    const data = await helpers.getSsmVar('StripeSecretKey');
    expect(data).toEqual(mockedResponseData);
    expect(ssm.getParameter).toBeCalledWith({ Name: `/mybox/StripeSecretKey`, WithDecryption: true });
    expect(ssm.getParameter().promise).toBeCalledTimes(1);
  });
});

100%覆盖的单元测试结果:

PASS  src/stackoverflow/56821395/index.spec.js
  helpers
    ✓ get parameter (8ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.872s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56821395

gwbalxhn

gwbalxhn2#

对我来说,它可以模拟函数,就像这样。

route53.createHostedZone = jest.fn().mockImplementation(() => ({
    promise: jest.fn().mockResolvedValue(mockCreatedHostedZone),
}));

相关问题