Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
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.


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

npm install -g jest


More From » node.js


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:


[#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.

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

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