gpt4 book ai didi

javascript - 模块功能上的 sinon stub

转载 作者:行者123 更新时间:2023-11-30 14:36:55 24 4
gpt4 key购买 nike

我正在尝试测试一个 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;

我的类.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com