我正在尝试测试一个 es6 类,但我不知道如何使用 sinon 来 stub 函数模块。 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;
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);
});
});
我尝试在 soapModule 上 stub ,但生成此错误:
Cannot stub non-existent own property callSoap
最佳答案
最后,我不得不将模块更改为 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
}
)
});
});
关于javascript - 模块功能上的 sinon stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298326/