Reputation: 1441
I need to write unit test cases in jasmine (& karma) for something like below. It uses rollup
to compile it.
const A = () => {
B();
}
const B = ()=> {
console.log("B is called");
}
exports {A}
In here my test.js
file, I need to check whether the B() is called, when we call A(). So I try something like this.
import * as mainFunctions from 'main.js'
describe("" , function() {
beforeEach(()=> {
spyOn(mainFunctions, 'B');
A();
});
it("", function() {
expect(mainFunctions.B).toHaveBeenCalled();
});
});
But it gives me the error "Error: : B is not declared writable or has no setter" when I run the test. Please suggest me a method to overcome this.
Upvotes: 0
Views: 279
Reputation: 2531
B
is private for all intents and purposes (it's not exported) and you should not directly test private methods.
What you can test is the effect of A
. We expect
that when A
is called console.log
will trigger. So you can test the effect by spying on console.log
.
console.log
in this case is a module dependency. When writing Unit-Test you should mock (spy) on all used dependencies and call all the available public methods.
spyOn(console, 'log');
...
it('should print log to console', function(){
mainFunctions.A();
expect(console.log).toHaveBeenCalled();
})
Note:
console
should not be used directly (or mocked) in production. You should implement aLoggerService
(see: winston) and spy on it instead.
Upvotes: 1