Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sinon stub on module function

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

like image 650
Felipe Nuñez Avatar asked Jan 25 '26 12:01

Felipe Nuñez


1 Answers

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
       }
    )
  });
});
like image 107
Felipe Nuñez Avatar answered Jan 27 '26 01:01

Felipe Nuñez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!