我试图在我的AWS项目上获得100%的覆盖率,但是我不知道如何模拟不接受参数的方法,并且应该通过使它们正常工作(返回值)的测试。使他们抛出错误的测试。我无法更改正在使用的技术,因此请尝试帮助我解决当前使用的问题。
我正在使用Nodejs,Typescript,Mocha,Chai,nyc和模拟需求进行模拟。
这是一个AWS项目,所以我正在使用AWS方法
这里是函数和方法,我在嘲笑describeAutoScalingGroups()
b = "x^3 + x - 4".split(" ")
b = [x for x in b if x != '+']
#combine "-" with next element
这是应该失败的测试(上面有对同一函数的测试,它将返回常规值)
export async function suspendASGroups() {
const autoscaling = new AWS.AutoScaling();
const asgGroups = await autoscaling.describeAutoScalingGroups().promise();
if (!asgGroups.AutoScalingGroups) {
throw new Error("describeAutoScalingGroups inside of suspendAGSGroups didn't return any groups");
}
// some other stuff below
这是模拟代码
it('Should throw an error, should fail', async () => {
assertNative.rejects(awsFunctions.resumeAGSGroups());
try {
let result = await awsFunctions.suspendASGroups();
} catch (e) {
assert.isTrue(
e.name == 'Error' &&
e.message == "describeAutoScalingGroups inside of suspendAGSGroups didn't return any groups",
'describeAutoScalingGroups in suspendAGSGroups didnt have the proper error message'
);
}
});
我希望能够通过两个测试,一个期望一个常规值的测试,另一个期望它引发错误的测试
这是相关报道的图片:https://i.imgur.com/D6GX0tf.png
我希望红色部分消失:)
谢谢
答案 0 :(得分:0)
在您的模拟中,您需要为AutoScalingGroupsType
返回一些结果为false的东西,因为您有以下检查:
if (!asgGroups.AutoScalingGroups) { ... }
所以您可以简单地做到这一点:
public describeAutoScalingGroups() {
return {
promise: () => {
return { AutoScalingGroups: false }
}
};
答案 1 :(得分:0)
我在reddit上得到了答案,所以我也将其发布在这里:
每个测试都需要一个不同的模拟。您应该在要从摩卡https://mochajs.org/#hooks获得的每个挂钩之前/之前设置模拟。
使用sinon可以使模拟创建更加整洁,但是如果您坚持使用模拟要求,那么您似乎需要使用https://www.npmjs.com/package/mock-require#mockrerequirepath ---评论结束
我是怎么做到的:
我制作了另一个与常规模拟文件相同的模拟文件,除了该模拟文件只能使函数失败(很好) 这是TEST中的代码:
describe('Testing FAILING suspendAGSGroups', () => {
it('Should throw an error, should fail', async () => {
const mock = require('mock-require');
mock.stopAll();
let test = require('./test/mocks/indexFailMocks');
mock.reRequire('./test/mocks/indexFailMocks');
let awsFailing = mock.reRequire('./handler');
// the line above is pretty important, without it It wouldnt have worked, you need to reRequire something even if it's the code of it isn't changed(I only changed the MOCK file but I had to reRequire my main function)
try {
let result = await awsFailing.suspendASGroups();
} catch (e) {
assert.isTrue(
e.name == 'Error' &&
e.message == "describeAutoScalingGroups inside of
suspendAGSGroups didn't return any groups",
'describeAutoScalingGroups in suspendAGSGroups didnt have the proper
error message'
);
}
});
});