Mocking chained methods - javascript

(I use Jest for testing)
For example, I have this function:
const find = () => {
return {
where: () => {
in: () => {}
}
};
};
and I call that in different place:
find('me').where('id').in(['123']);
How to mock and test calls in find(), where() and in()?

Here's a dirt simple mock interface:
const find = (findData) => {
const data = {
find: findData
};
const self = {
where: (whereData) => {
data.where = whereData;
return self;
},
in: (inData) => {
data.in = inData;
return self;
},
data
};
return self;
};
const res = find('me').where('id').in(['123']);
console.log(res.data);

Related

How do these nested JavaScript functions work?

I have a question related to this code:
const somaHorasExtras = (salario, valorHorasExtras) => salario + valorHorasExtras;
const calculaDescontos = (salario, descontos) => salario - descontos;
const verifiqueSe = (valor) => {
const assercoes = {
ehExatamenteIgualA(esperado) {
if (valor !== esperado) {
// eslint-disable-next-line no-throw-literal
throw {};
}
},
};
return assercoes;
};
const teste = (titulo, funcaoDeTeste) => {
try {
funcaoDeTeste();
console.log(`${titulo} passou!`);
} catch {
console.error(`${titulo} não passou!!!`);
}
};
teste('somaHorasExtras', () => {
const esperado = 2500;
const retornado = somaHorasExtras(2000, 500);
verifiqueSe(retornado).ehExatamenteIgualA(esperado);
});
teste('calculaDesconto', () => {
const esperado = 2300;
const retornado = calculaDescontos(2500, 200);
verifiqueSe(retornado).ehExatamenteIgualA(esperado);
});
My question is related to the verifiqueSe function specifically. How does this function work? Does someone can explain how this function work in conjunction with the inner function ehExatamenteIgualA? What is the assercoes which is returned?
Thank you.
Your verifiqueSe(valor) function returns an object. You may find it a little confusing, since this syntax:
const foo = {
bar() {
//
}
};
is just a short syntax for object method:
const foo = {
bar: function () {
//
}
};
So in order to call the bar() function, you'd need to reach it through foo:
foo.bar();

mocking private methods to test an exported method fails in jest

I'm having an actual class like this
my-file.js
const methodA = () => { return 'output-from-methodA'; }
const methodB = () => { const b = methodA(); b.c = "out-put bind"; return b; }
module.exports = {
methodB
}
my-file.test.js
const { methodA, methodB } = require('./my-file.js');
describe('methodB testing', () => {
it('should call methodA', () => {
methodB();
expect(methodA).toHaveBeenCalled()
}
});
here methodA is private method, so it is not explicit to the test file, then how i ensure it is called or not in the test files
There is no way to test the private function, only the alternative way found is to test the outputs like
const { methodA, methodB } = require('./my-file.js');
describe('methodB testing', () => {
it('should call methodA', () => {
const result = methodB();
expect(result.b.c).toBe("out-put bind")
}
});

How to call a function from a nested object?

I have an object called obj that has a nested object comments and a function startMatch that returns an object like this:
var obj = {};
obj.comments = {
startMatch: function(matchStrings, isCaseSensitive) {
return {
subscribe: function(delegate) {
delegate('test')
const unsubscribe = () => {
console.log("unsubscribed");
};
}
};
}
};
var subscription = obj.comments.startMatch([], false).subscribe(function(result) {
console.log(result)
});
I would like to make this in such a way that I could call the unsubscribe function like this:
subscription.unsubscribe();
But I can't figure out how to do it without getting the unsubscribe undefined error.
Choose the simplest way:
var obj = {};
obj.comments = {
startMatch: function(matchStrings, isCaseSensitive) {
return {
subscribe: function(delegate) {
delegate('test');
return { unsubscribe: () => console.log("unsubscribed") }
}
};
}
};
var subscription = obj.comments.startMatch([], false).subscribe(function(result) {
console.log(result)
});
subscription.unsubscribe();

How to test javascript class using jest?

trying to test class using jest its throwing declaration exception , what would be correct approach to test class in below scenario and test promise chain?
main.ts
export class ModuleExecutor {
public execute(moduleName: string): (param1, param2) => any {
const self = this;
return function(params: any, responseCallback: (param: any, param2: any) => any) {
let _mod;
let _httpRequest;
let _params;
Promise.resolve(getApiModule(self.identity, moduleName))
.then((mod: ModuleBase < any, any > ) => {
_mod = mod;
mod.ExecStage = ExecStage.Init;
// #ts-ignore - red squiggly for the return mismatch which are resolved in Grunt
return mod.init(getHttpModule(self.identity), params);
});
}
}
}
main.spec.ts
describe("Test promise chaining with Mock functions", () => {
const myMockFuncExecute = jest.fn((mod: ModuleBase<any, any>) => {
_mod = mod;
_mod.ExecStage = ExecStage.Init;
const ret = _mod.Init(getHttpModule(Identity.node), params);
Promise.resolve(ret);
});
jest.mock("./main.ts");
const executerClass = require("./main.ts");
executerClass.mockImplementation(() => {
return {
init: myMockFuncExecute
};
});
it('it should get Modulebase', async () => {
const _result = new executerClass(Identity.node);
_result.execute("Payments/url").then(myMockFuncExecute())
.then((module) => {
const mod = module;
expect(mod).toEqual(ModuleBase);
});
});
});

Mocking complex module using Jest.js

This is what the module I want to mock looks like:
class TheModule {
constructor() {
this.subClass = new SubClass();
}
}
class SubClass {
constructor() {
this.someMethod = () => 'Did Something great';
}
}
module.exports = TheModule;
This is TheModule usage I want to test:
const TheModule = require('./TheModule');
const method = () => {
const theModule = new TheModule();
return theModule.subClass.someMethod();
}
module.exports = method;
This is my test:
describe('method test', () => {
it('should return "Test pass"', () => {
jest.doMock('./TheModule');
const theModuleMock = require('./TheModule');
const method = require('./TheModuleUsage');
const mock = () => 'Test pass';
theModuleMock.subClass.someMethod.mockImplementation(() => mock);
expect(method()).toEqual('Test pass');
});
});
When I run this test I get TypeError: Cannot read property 'someMethod' of undefined
Is it possible to mock this module without changing TheModule implementation?
If you will export SubClass you can mock it without changing TheModule but in your case you should mock SubClass property in TheModule explicitly with factory for example:
describe('method test', () => {
it('should return "Test pass"', () => {
let mockedSomeMethod = jest.fn().mockImplementation(() => 'Test pass');
jest.doMock('./TheModule', () => {
// mock constructor
return jest.fn().mockImplementation(() => {
return { subClass: { someMethod: mockedSomeMethod } }
});
});
const method = require('./TheModuleUsage');
expect(method()).toEqual('Test pass');
});
});

Categories