Friday 26 April 2019

How to mock a method that accepts no arguments and its supposed to work normally in 1 test, and supposed to throw an error in another test

I'm trying to get 100% coverage on my AWS project but I don't know how to mock methods that don't accept arguments AND are supposed to pass a test that makes them work properly(return values) and another test that makes them throw an error. I can't change the tech I am using so please try to help me with the things I am using right now.I am using Nodejs, Typescript, Mocha, Chai, nyc and mock-require for mocking. (The way mock-require works is that when you require something, in this case "aws-sdk", it replaces all methods of it with my own)It's an AWS project so I am working with AWS methodsHere is the function and method, I am mocking describeAutoScalingGroups()​​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"); } ​This is the TEST that is supposed to fail(Above this there is a test of the same function which will return regular values)it('Should throw an error, should fail', async () => { try { let result = await awsFunctions.resumeAGSGroups(); } catch (e) { assert.isTrue( e.name == 'Error' && e.message == "describeAutoScalingGroups in resumeAGSGroups didn't return any groups", 'describeAutoScalingGroups in resumeAGSGroups didnt have the proper error message' ); } }); And here is the mock codeclass AutoScaling { constructor() { console.log('mock constructor called'); } public describeAutoScalingGroups() { const data = (): AWS.AutoScaling.Types.AutoScalingGroupsType => { return { // return some stuff }; return { promise: data }; } } I expect to be able to pass both tests, the one that expects a regular value and one that expects it to throw an errorhere is a picture of the coverage: https://i.imgur.com/D6GX0tf.pngI expect that red part to be gone :)Thank you

Submitted April 27, 2019 at 07:38AM by khazha88

No comments:

Post a Comment