Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  142] [ 5]  / answers: 1 / hits: 98161  / 6 Years ago, sat, december 2, 2017, 12:00:00

I'm a newbie to Jest. I've managed to mock my own stuff, but seem to be stuck mocking a module. Specifically constructors.



usage.js



const AWS = require(aws-sdk)
cw = new AWS.CloudWatch({apiVersion: 2010-08-01})
...
function myMetrics(params) {
cw.putMetricData(params, function(err, data){})
}


I'd like to do something like this in the tests.



const AWS = jest.mock(aws-sdk)
class FakeMetrics {
constructor() {}
putMetricData(foo,callback) {
callback(null, yay!)
}
}

AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())


However when I come to use it in usage.js the cw is a mockConstructor not a FakeMetrics



I realise that my approach might be 'less than idiomatic' so I'd be greatful for any pointers.



This is a minimal example https://github.com/ollyjshaw/jest_constructor_so



npm install -g jest



jest


More From » node.js

 Answers
14

The problem is how a module is being mocked. As the reference states,




Mocks a module with an auto-mocked version when it is being required.
<...>
Returns the jest object for chaining.




AWS is not module object but jest object, and assigning AWS.CloudFormation will affect nothing.



Also, it's CloudWatch in one place and CloudFormation in another.



Testing framework doesn't require to reinvent mock functions, they are already there. It should be something like:



const AWS = require(aws-sdk);
const fakePutMetricData = jest.fn()
const FakeCloudWatch = jest.fn(() => ({
putMetricData: fakePutMetricData
}));
AWS.CloudWatch = FakeCloudWatch;


And asserted like:



expect(fakePutMetricData).toHaveBeenCalledTimes(1);

[#55785] Tuesday, November 28, 2017, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;