Unable to stub an exported function with Sinon - node.js

I need to test the following createFacebookAdVideoFromUrl() that consumes a retryAsyncCall that I'd like to stub with Sinon :
async function createFacebookAdVideoFromUrl(accountId, videoUrl, title, facebookToken = FACEBOOK_TOKEN, options = null, businessId = null) {
const method = 'POST';
const url = `${FACEBOOK_URL}${adsSdk.FacebookAdsApi.VERSION}/${accountId}/advideos`;
const formData = {
access_token: businessId ? getFacebookConfig(businessId).token : facebookToken,
title,
name: title,
file_url: videoUrl,
};
const callback = () => requestPromise({ method, url, formData });
const name = 'createFacebookAdVideoFromUrl';
const retryCallParameters = buildRetryCallParameters(name, options);
const adVideo = await retryAsyncCall(callback, retryCallParameters);
logger.info('ADVIDEO', adVideo);
return { id: JSON.parse(adVideo).id, title };
}
This retryAsyncCall function is exported as such:
module.exports.retryAsyncCall = async (callback, retryCallParameters, noRetryFor = [], customRetryCondition = null) => {
// Implementation details ...
}
Here is how I wrote my test so far:
it.only("should create the video calling business's Facebook ids", async () => {
const payload = createPayloadDataBuilder({
businessId: faker.internet.url(),
});
const retryAsyncCallStub = sinon.stub(retryAsyncCallModule, 'retryAsyncCall').resolves('random');
const createdFacebookAd = await FacebookGateway.createFacebookAdVideoFromUrl(
payload.accountId,
payload.videoUrl,
payload.title,
payload.facebookToken,
payload.options,
payload.businessId,
);
assert.strictEqual(retryAsyncCallStub.calledOnce, true);
assert.strictEqual(createdFacebookAd, { id: 'asdf', title: 'asdf' });
});
I don't expect it to work straightaway as I am working in TDD fashion, but I do expect the retryAsyncCall to be stubbed out. Yet, I am still having this TypeError: Cannot read property 'inc' of undefined error from mocha, which refers to an inner function of retryAsyncCall.
How can I make sinon stubbing work?

I fixed it by changing the way to import in my SUT :
// from
const { retryAsyncCall } = require('../../../helpers/retry-async');
// to
const retry = require('../../../helpers/retry-async');
and in my test file :
// from
import * as retryAsyncCallModule from '../../../src/common/helpers/retry-async';
// to
import retryAsyncCallModule from '../../../src/common/helpers/retry-async';
The use of destructuring seemed to make a copy instead of using the same reference, thus, the stub was not applied on the right reference.

Related

jest.spy on a global function is ignored when the spy is called from another function

I'm working on a legacy JS web project that doesn't use import/require etc. So if I want to write tests, I need to somehow load all the code before the test is executed (I'm using a custom testEnvironment for that).
I've created a sample repo here.
Here are the main files:
// ./src/index.js
function spyOnMe() {
return "Hello World!";
}
function main() {
const text = spyOnMe();
return text;
}
// ./src/index.spec.js
it('should spyOn spyOnMe', () => {
const mockedValue = 'Thanks for helping!';
jest.spyOn(window, 'spyOnMe').mockReturnValue(mockedValue);
expect(spyOnMe()).toBe(mockedValue); // OK
const result = main();
expect(result).toBe(mockedValue); // KO
});
// ./jest.config.js
module.exports = {
clearMocks: true,
coverageProvider: "v8",
testEnvironment: "./jest.env.js",
};
// ./jest.env.js
const JSDOMEnvironment = require("jest-environment-jsdom");
const vm = require("vm");
const fs = require("fs");
class MyEnv extends JSDOMEnvironment.default {
constructor(config, context) {
super(config, context);
this.loadContext();
}
loadContext() {
const js = fs.readFileSync("./src/index.js", "utf8");
const context = vm.createContext();
context.document = this.global.document;
context.window = this.global.window;
vm.runInContext(js, context, {
filename: "./src/index.js",
displayErrors: true,
});
Object.assign(this.global, context);
}
}
module.exports = MyEnv;
The issue is in the index.spec.js:
The first expect returns Thanks for helping!
The second one returns "Hello world!"
Why is that?
I found a fix but I don't really understand why it works:
In jest.env.js, I should replace this line:
- const context = vm.createContext();
+ const context = vm.createContext(this.global);

mock transaction in runTransaction

i want to mock code inside a runTransaction function.
example code:
await admin.firestore().runTransaction(async transaction => {
const hubDocument = admin.firestore().collection("Acme").doc('4');
const hubData = (await transaction.get(hubDocument)).data();
newData = {
...hubData,
someAttribute: 'some new value'
};
transaction.update(hubDocument, newData);
})
i want to mock transaction, check if it is called with the right data etc.pp.
I managed to mock firestore() but do not know how to mock the transaction parameter.
I have not tested this, but I asume something like this should do the trick:
import { Transaction } from '#google-cloud/firestore';
const origTransactionGet = Transaction.prototype.get
Transaction.prototype.get = function () {
console.log(arguments, "< Intercepted Transaction.prototype.get")
return origTransactionGet.apply(this, arguments)
}
// your code
await admin.firestore().runTransaction(async transaction => {
const hubDocument = admin.firestore().collection("Acme").doc('4');
const hubData = (await transaction.get(hubDocument)).data();
newData = {
...hubData,
someAttribute: 'some new value'
};
transaction.update(hubDocument, newData);
})
As #FiodorovAndrei commented, the alternative, perhaps more comfortable if you use jest would be to just use firestore-jest-mock to mock the Firestore functionality.

sinon stub calls fake calling actual function

I'm having situation where I want to write unit test cases for a function to make sure if it is working fine or not. So I have created stub for that specific function and when I tries to calls fake that stub, the function is actually getting called instead of fake call. Below is my scenario:
I have an main function from where I'm calling the function saveData(**).
saveData(**) function is calling AWS SQS to save an message to DB
Below is my main function:
'use strict';
async function mainFunction() {
try {
await saveData(
name,
age,
);
return true;
} catch (e) {
console.log('Error - [%s]', e);
return null;
}
}
module.exports = { mainFunction };
Below is my saveData(**) function:
'use strict';
const AWS = require('aws-sdk');
const sqs = new AWS.SQS();
const saveData = async (
name,
age,
) => {
await sendMessage(JSON.stringify(dbData));
const params = {
DelaySeconds: <some_delay>,
MessageAttributes: <messageAttributes>,
MessageBody: {name:name, age:age},
QueueUrl: <URL_FOR_QUEUE>,
};
return sqs.sendMessage(params).promise();
return true;
};
module.exports = {
saveData,
};
And my test case is,
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
require('app-module-path').addPath('./src');
const sinon = require('sinon');
const app = express();
const sqsSender = require('lib/queue');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const main = require('../../../src/main-function');
const routes = require('routes');
routes.configure(app);
let mainFunctionStub;
let saveDataStub;
describe('/v1/main', () => {
beforeEach(() => {
mainFunctionStub = sinon.stub(main, 'mainFunction');
saveDataStub = sinon.stub(sqsSender, 'saveData');
});
describe('Test', () => {
it(`should return success`, (done) => {
const name = 'Name';
const age = 'Age';
saveDataStub.resolves({
name,
age,
});
});
});
afterEach(() => {
mainFunctionStub.restore();
mainFunctionStub.reset();
saveDataStub.restore();
saveDataStub.reset();
});
});
But this test is returning,
error: Jun-20-2021 20:07:05: Error - [Error [ConfigError]: Missing region in config
and,
Error: Timeout of 3500ms exceeded.
From this error I can say that this is actually calling SQS function instead of faking. How can I resolve this or how can I fake call to this function? I'm new to this unit testing so any help would be appriciated.
Stubbing works by replacing the property on the exports object. Since the require happens before sinon replaces the function, you capture the reference to the original function instead of dynamically using the currently set one.
You haven't showed your require calls in the main file, but from the call-site I infer you're importing it like const { saveData } = require('../foo/sqsSender'). This means you're grabbing the function off of the object when first loading the code. If you instead keep a reference to the sqsSender module instead, and reference the function on invocation, the stub should work.
'use strict';
// Don't destructure / grab the function.
const sqsSender = require("../foo/sqsSender")+
async function mainFunction() {
try {
// Use reference through module
await sqsSender.saveData(
name,
age,
);
return true;
} catch (e) {
console.log('Error - [%s]', e);
return null;
}
}
module.exports = { mainFunction };

How can I mock this http request using jest?

I am new to using Jest for unit tests. How can I mock this simple http request method "getData"? Here is the class:
const got = require("got")
class Checker {
constructor() {
this.url
this.logData = this.logData.bind(this);
this.getData = this.getData.bind(this);
}
async getData(url) {
const response = await got(url);
const data = await response.body;
return data;
}
async logData(first, second, threshold) {
let data = await this.getData(this.url)
console.log("received " + data.body);
}
}
I am trying to mock "getData" so I can write a unit test for "logData". Do I need to mock out the entire "got" module? Thanks.
If you change invoking got to got.get you should be able to have a working test like so:
const got = require('got');
const Checker = require('../index.js');
describe("some test", () => {
beforeEach(() => {
jest.spyOn(got, 'get').mockResolvedValue({ response: { body: { somekey: "somevalue" } } } );
});
it("works", async () => {
new Checker().getData();
expect(got.get).toBeCalledTimes(1);
})
})
One approach is to use dependency injection. Instead of calling 'got' directly, you can 'ask for it' in the class constructor and assign it to a private variable. Then, in the unit test, pass a mock version instead which will return what you want it to.
const got = require("got");
class Checker {
constructor(gotService) {
this.got = gotService;
this.logData = this.logData.bind(this);
this.getData = this.getData.bind(this);
}
async getData(url) {
const response = await this.got(url);
const data = await response.body;
return data;
}
async logData(first, second, threshold) {
let data = await this.getData(this.url)
console.log("received " + data.body);
}
}
//real code
const real = new Checker(got);
//unit testable code
const fakeGot = () => Promise.resolve(mockedData);
const fake = new Checker(fakeGot);
Here is what we are doing:
'Inject' got into the class.
In the class, call our injected version instead of directly calling the original version.
When it's time to unit test, pass a fake version which does what you want it to.
You can include this directly inside your test files. Then trigger the test that makes the Http request and this will be provided as the payload.
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data: { eth: 0.6, btc: 0.02, ada: 1 } }),
})
);
it('should return correct mock token values', async () => {
const addresses = ["mockA", "mockB", "mockC"];
const res = await getTokenData(addresses);
expect(res.data).toEqual({ eth: 0.6, btc: 0.02, ada: 1 });
});

req object with express causes UnhandledPromiseRejectionWarning

I have adapted the below code from Google's Datastore tutorial. I'm vaguely aware of Promises, and I'm using await where I can figure out to do so. I've used the req object with express as below without incident, but it seems to be empty here.
It causes this error:
2021-04-16 04:55:03 default[20210415t215354] (node:10) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined
[SNIP]
name is a reference to a param I'm specifying like this:
curl -X POST https://MYURL/gizmos --data 'name=foo&type=bar&len=29'
What am I doing wrong? How do I avoid this?
/**
* #param {object} gizmo The gizmo record to insert.
*/
const insertGizmo = gizmo => {
return datastore.save({
key: datastore.key('gizmo'),
data: gizmo,
});
};
/**
* Retrieve the latest gizmo
*/
const getLastGizmo = () => {
const query = datastore
.createQuery('gizmo')
.order('createTime', {descending: true})
.limit(1);
return datastore.runQuery(query).then( (entities) => {
return entities[0].map(fromDatastore);
});
};
//Create a Gizmo
app.post('/gizmos', async (req, res, next) => {
const createTime = new Date();
const gizmo = {
name: req.body.name,
type: req.body.type,
length: req.body.len,
createTime: createTime,
};
try {
await insertGizmo(gizmo);
const newGizmo = await getLastGizmo();
//const [newGizmos] = await getLastGizmo();
await insertGizmo(gizmo);
const newGizmo = await getLastGizmo();
//const [newGizmos] = await getLastGizmo();
const gizmoUrl = "https://MYURL/gizmos/"+newGizmo.id;
const resText = {
"id" : newGizmo.id,
"name" : newGizmo.name,
"type" : newGizmo.type,
"length" : newGizmo.length,
"self" : gizmoUrl,
};
res.status(201).set('Content-Type', 'text/plain').send(resText).end();
} catch (error) {
next(error);
}
});
Per #hoangdv, add app.use(express.urlencoded()) somewhere. Rather node-ish not have it as the default if you ask me.

Resources