我读了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)
2条答案
按热度按时间a64a0gku1#
下面是解决方案,您可以手动使用
jest.mock()
模拟aws-sdk
。index.js
:index.spec.js
:100%覆盖的单元测试结果:
以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56821395
gwbalxhn2#
对我来说,它可以模拟函数,就像这样。