我正在尝试测试es6类,但我不知道函数模块whit sinon是多么残缺。 测试不是sm.callSoap函数下的覆盖行
我试试这个:
module.js
function soapModule(){
this.callSoap = (id) => {
....//some code
return new Promise((resolve,reject) =>{
return resolve("whatever");
}
}
}
index.js (这是模块的索引)
"use strict";
var soapModule = require('./module/module');
module.exports.soapModule = soapModule;
我-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);
});
});
我尝试在 soapModule 上存根,但会生成此错误:
不能存根不存在的自有属性callSoap
答案 0 :(得分:2)
最后,我不得不将模块更改为ECMAScript 6语法。
所以,我的新模块看起来像这样:
<强> module.js 强>
export function callSoap(id){
....//some code
return new Promise((resolve,reject) =>{
return resolve("whatever");
}
}
当我改为ECMAScript 6语法时,我实现了babel-cli编译为EC5,所以索引改为:
var soapModule = require('./module/module');
到
var soapModule = require('./lib/module'); //<-- this is the build output folder
然后,单元测试看起来像这样:
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
}
)
});
});
答案 1 :(得分:0)
我还注意到你已经存根了soapModule实例的callSoap方法。它需要是soapModule原型的存根,所以当你在myMethod中创建一个实例时,它就有了存根版本。
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);
});
});