How to mock methods for writing unit tests in nodejs [duplicate] - node.js

I can't figure out a way to stub a function called from within the same module this function is defined (the stub does not seem to work). Here's an example:
myModule.js:
'use strict'
function foo () {
return 'foo'
}
exports.foo = foo
function bar () {
return foo()
}
exports.bar = bar
myModule.test.js:
'use strict'
const chai = require('chai')
const sinon = require('sinon')
chai.should()
const myModule = require('./myModule')
describe('myModule', () => {
describe('bar', () => {
it('should return foo', () => {
myModule.bar().should.equal('foo') // succeeds
})
describe('when stubbed', () => {
before(() => {
sinon.stub(myModule, 'foo').returns('foo2') // this stub seems ignored
})
it('should return foo2', () => {
myModule.bar().should.equal('foo2') // fails
})
})
})
})
This reminds me of Java static functions which are not stubbable (almost).
Any idea how to achieve what I'm trying to do? I know that extracting foo in a different module will work, but that's not what I'm trying to do here. I'm also aware that invoking foo in the bar method with the keyword this will also work, I'm puzzled toward the use of ̀this in this context (since I'm not using OOP).

I just tested this. And it works like charm.
'use strict'
function foo () {
return 'foo';
}
exports.foo = foo;
function bar () {
return exports.foo(); // <--- notice
}
exports.bar = bar;
Explanation
when you do sinon.stub(myModule, 'foo').returns('foo2') then sinon stubs the exported object's foo not the actually foo function from inside your myModule.js ... as you must know, foo is in accessible from outside the module. So when you set exports.foo, the exported object exports.foo stores the ref of foo. and when you call sinon.stub(myModule, 'foo').returns('foo2'), sinon will stub exports.foo and not the actual foo
Hope this makes sense!

I was a bit wary of using exports since it's a bit magical (for instance when you're coding in Typescript, you never use it directly), so I'd like to propose an alternate solution, which still requires modifying the source code unfortunately, and which is simply to wrap the function to be stubbed into an object:
export const fooWrapper = {
foo() {...}
}
function bar () {
return fooWrapper.foo()
}
And sinon.stub(fooWrapper, 'foo'). It's a bit a shame having to wrap like that only for testing, but at least it's explicit and type safe in Typescript (contrary to to exports which is typed any).

Related

importing and calling a function in Typsescript which returns nothing

Hi I have a function in typescript which returns nothing. When I try to import and call this function in another part of my app, I am getting errors. I am fairly new to typescript and am struggling with how to fix this issue.
Here's my code. I am trying to set up a few scripts to do some simple tests (would prefer not to use any testing frameworks).
My helper functions for testing are here
//File: helper.ts
type validator = () => void;
export const it = (desc: string, fn: validator) => {
try {
let res = fn();
console.log("\x1b[32m%s\x1b[0m", `\u2714 ${desc}`);
} catch (error) {
console.log("\n");
console.log("\x1b[31m%s\x1b[0m", `\u2718 ${desc}`);
console.error(error);
}
};
My tests use the helpers and are defined like this;
// File: dummytests.ts
import { strict as assert } from 'node:assert';
import { it } from "src/spec/helper";
export const check_if15_eqls_15 = it("shoulld check if something is true", () => {
assert.strictEqual(15, 15);
});
and i finally am running the tests as such;
// File: testRUnner.ts
import {check_if15_eqls_15} from 'src/spec/frontend/dummyTests';
console.log ("This test harness is for the frontend tests.\n");
check_if15_eqls_15();
this throws the error;
error TS2349: This expression is not callable.
Type 'void' has no call signatures.
5 check_if15_eqls_15();
~~~~~~~~~~~~~~~~~~
The line
export const check_if15_eqls_15 = it("shoulld check if something is true", () => {
assert.strictEqual(15, 15);
});
already calls the method.
This means check_if15_eqls_15 is already the return value of the method and unless the return value is not another function (which it isn't in this case), you can't call it again.
The same thing would happen in pure JS, since TypeScript does not change how the code is run
Something that might work for your example would be this:
export const check_if15_eqls_15 = () => it("shoulld check if something is true", () => {
assert.strictEqual(15, 15);
});

Failing to mock declared functions with jest.spyOn

I'm under the impression that jest.spyOn.mockImplementationOnce can mock a function as long as it is implemented as a function expression, but might fail to mock when the function is written as a function declaration. Why is it behaving like that?
I have one TS file in the folder */this_works with the following code:
export function myFunction() {
return myOtherFunction();
}
export const myOtherFunction = function() {
return 'something';
};
And then another TS file in the folder */this_doesnt with the following code:
export function myFunction() {
return myOtherFunction();
}
export function myOtherFunction() {
return 'something';
}
The only difference between them is that myOtherFunction is either a function declaration or a function expression.
Both files are submitted to the same test with jest.
import * as myModule from '../index';
describe('myFunction', () => {
it('does something', () => {
jest
.spyOn(myModule, 'myOtherFunction')
.mockImplementationOnce(
function() {
return 'hello jest';
},
);
const result = myModule.myFunction();
expect(result).toEqual('hello jest');
});
});
All code can be found at my playground repo's folder
The result is that the function expression is mocked and the test passes, while the function declaration is not mocked and the test fails.
Anecdotally, this seems to only happen if the function being mocked is not being called directly, instead it is being called by another function. When the declared function gets called directly, the test passes.
I would like to understand why that is so I can write better tests.

How to mock a function which is being called by another function?

I am using Jest to unit test my modules. I have a module say fooModule.ts.
I have 3 functions inside export const foo = () => {}, export const bar = () => {}, export const baz = () => {}. Now the function foo() internally calls bar and baz. Now these two methods are what I want to mock to give different results to foo. How do I proceed forward with this?
I tried using mockImplementation, but later I found out that made no sense.

Mocha unit testing: where to create variables

I'm just getting into unit testing for the first time. Using Mocha in Node as the testing framework. All the examples I've come across create variables inside the it(). Does it matter if they are created inside or outside of it()? For example, if I have multiple it()s inside a describe(), and I need the same mocked data across all of the it()s. I'd rather not re-create the same variable repeatedly, if possible.
describe ('MyClass', function () {
let myObj = new MyObj // Mock data here
it ('Should be...', function () {
....
})
it ('Should be...', function () {
....
})
...
})
It's totally acceptable to have variables live outside of your individual it blocks, but it may not be appropriate depending on your use case.
For objects that you do not expect to change, Object.freeze is an option: const myObj = Object.freeze(new MyObj).
If you expect your tests to change your object, you should use beforeEach to ensure that they are restored to the proper state; this will prevent your it blocks from polluting one another and avoid an unpleasant debugging journey.
For example:
describe('MyClass', function () {
let myObj
beforEach(() => {
myObj = new MyObj()
})
it('changes myObj', () => {
changeProp(myObj.sum)
expect(myObj.sum).toEqual(4)
})
it('depends on myObj being the same', () => {
expect(myObj.sum).toEqual(2)
})
})
Alternately, you can eschew the fat arrow syntax and rely on the shared context between blocks in mocha:
beforeEach(function () {
this.myObj = new MyObj()
})
it('changes myObj', function () {
addTwo(this.myObj.sum)
expect(this.myObj.sum).toEqual(4)
})
it('depends on myObj being the same', function () {
expect(this.myObj.sum).toEqual(2)
})

Sinon function stubbing: How to call "own" function inside module

I am writing some unit tests for node.js code and I use Sinon to stub function calls via
var myFunction = sinon.stub(nodeModule, 'myFunction');
myFunction.returns('mock answer');
The nodeModule would look like this
module.exports = {
myFunction: myFunction,
anotherF: anotherF
}
function myFunction() {
}
function anotherF() {
myFunction();
}
Mocking works obviously for use cases like nodeModule.myFunction(), but I am wondering how can I mock the myFunction() call inside anotherF() when called with nodeModule.anotherF()?
You can refactor your module a little. Like this.
var service = {
myFunction: myFunction,
anotherFunction: anotherFunction
}
module.exports = service;
function myFunction(){};
function anotherFunction() {
service.myFunction(); //calls whatever there is right now
}

Resources