Reputation: 83
i'm trying test a es6 class, but i don't know how stub a function module whit sinon. The test not coverage line under sm.callSoap function
I try this:
module.js
function soapModule(){
this.callSoap = (id) => {
....//some code
return new Promise((resolve,reject) =>{
return resolve("whatever");
}
}
}
index.js (this is the index of the module)
"use strict";
var soapModule = require('./module/module');
module.exports.soapModule = soapModule;
my-class.js
import {soapModule} from "soap-client"
export default class MyClass {
constructor(){
console.log("instance created");
}
myMethod(id){
let sm = new soapModule();
return sm.callSoap(id)
.then(result => {
console.log(result);
}).catch(e => {
console.log("Error :" + e);
})
}
}
test.js
import MyClass from "../src/my-class";
import {soapModule} from "soap-client";
import sinon from 'sinon';
describe("Test MyClass",()=>{
let myclass;
let soap;
let stub;
before(()=>{
myclass = new MyClass();
soap = new soapModule();
stub = sinon.stub(soap,'callSoap');
});
it("test a", ()=>{
let fakeout = {
resp : "tada!"
}
stub.resolves(fakeout);
myclass.myMethod(1);
});
});
i try to stub on soapModule but generate this error:
Cannot stub non-existent own property callSoap
Upvotes: 3
Views: 5678
Reputation: 83
finally, i had to change the module to ECMAScript 6 syntax.
so, my new module looks like this:
module.js
export function callSoap(id){
....//some code
return new Promise((resolve,reject) =>{
return resolve("whatever");
}
}
when I change to ECMAScript 6 syntax, i implement babel-cli to compile to EC5, so the index change from:
var soapModule = require('./module/module');
to
var soapModule = require('./lib/module'); //<-- this is the build output folder
then, the unit-test looks like this:
import MyClass from "../src/my-class";
import {soapModule} from "soap-client";
import sinon from 'sinon';
describe("Test MyClass",()=>{
let myclass;
let stub;
before(()=>{
myclass = new MyClass();
stub = sinon.stub(soap,'callSoap');
});
it("test a", ()=>{
let fakeout = {
resp : "tada!"
}
stub.resolves(fakeout);
myclass.myMethod(1).then(result =>{
console.log(result) //<----- this is the fakeout
}
)
});
});
Upvotes: 2
Reputation: 17319
I also noticed that you had stubbed the callSoap method of an instance of soapModule. It needs to be the stubbed on the prototype of soapModule so when you create an instance inside of myMethod it has the stubbed version.
import MyClass from "../src/my-class";
import {soapModule} from "soap-client";
import sinon from 'sinon';
describe("Test MyClass",()=>{
let myclass;
let stub;
let stubP;
before(()=>{
myclass = new MyClass();
stub = sinon.stub(soapModule.prototype, 'callSoap');
stubP = sinon.stub(); // second stub to be used as a promise
stub.returns(stubP);
});
after(() => {
stub.restore();
});
it("test a", ()=>{
let fakeout = {
resp : "tada!"
}
myclass.myMethod(1);
stubP.resolves(fakeout);
});
});
Upvotes: 0