A little new the JS and trying to test a function that I made using sinon. For my current setup I have a util.js
const { v4: uuidv4 } = require("uuid");
function generateUUID () {
return uuidv4();
}
module.exports = { generateUUID }
a dynamo.js helper file
const AWS = require("aws-sdk");
async function doesVarExist(var){
//call to dynamo table to check if an obj exists. Returns a bool value
}
module.exports = { doesVarExist }
and createObject.js file
const util = require("./util");
const dynamo = require("./dynamo");
class CustomObj {
constructor(uuid, variable1, variable2) {
this.uuid = uuid;
this.var1 = variable1;
this.var2 = variable2;
}
}
async function createObject(var1, var2) {
if(dynamo.doesVarExist(var1)) {
const newObj = new CustomObj(
util.generateUUID(),
var1,
var2
);
}
return newObj;
}
module.exports = { CustomObj, createObject }
In the test itself, I’m attempting to stub both the doesVarExist method and the generateUUID method but for some reason, the sinon stub seems to be ignored.
createObject.test.js
const chai = require("chai");
const { expect } = require("chai");
const chaiAsPromised = require("chai-as-promised");
const sinon = require("sinon");
const rewire = require("rewire");
const dynamo = rewire("../../src/dynamo");
const createCustomObjects = rewire("../../src/createObject");
const util = require("../../src/util");
chai.use(chaiAsPromised);
describe("generate object and metadata", () => {
afterEach(() => {
sinon.restore();
});
it("createObject", async () => {
sinon.stub(util, "generateUUID").returns("Random1234");
let objExistStub = sinon.stub(dynamo, "doesVarExist").returns(false);
createCustomObjects.__set__("doesVarExist", objExistStub);
const expected = //created expected object here
const result = await createCustomObjects.createObject("random1", "random2");
expect(result).to.deep.equal(expected);
});
});
However what ends up happening is that the doesVarExist function actually does try to make the dynamo call, which then times out. When I tried removing the doesVarExist function call in the code, the generateUUID function also does not work and gives me a random one instead of the seeded value. Any help is appreciated!