【问题标题】:How to mock non class member function using sinon如何使用 sinon 模拟非类成员函数
【发布时间】:2019-04-18 15:30:14
【问题描述】:

我需要在 method2 函数中添加模拟。但我收到错误

“TypeError:试图将未定义的属性method2包装为函数”

class ServiceClass {

  async method1() {

  }

}

async function method2() {}

module.exports = ServiceClass;

【问题讨论】:

  • 你试过导出函数吗?到目前为止,您只是导出 ServiceClass,因此无法从外部访问 method2

标签: javascript testing mocha.js sinon


【解决方案1】:

您忘记导出异步方法2

// my-module.es6

export default class ServiceClass {

  async method1() {

  }

}

export async function method2() {}

// test.js

import { method2 } from 'my-module';

const spy = sinon.spy(method2);

但是,不清楚您是否打算将 method2 放在您的班级中?如果是这样的话,你会做和method1一样的事情,做这样的事情

// test.js

import ServiceClass from 'my-module';

const serviceClass = new ServiceClass();

const spy = sinon.spy(serviceClass, 'method2');

【讨论】:

  • 即使您导出方法,sinon 存根也不接受。但是我在method2中使用了其他一些库方法。我嘲笑了那个库并得到了预期的输出。感谢您的宝贵时间。
【解决方案2】:

在方法 2 中,我正在调用另一个方法 3。我在其中添加了模拟。不幸的是,导出 method2 并没有给出预期的输出。

async function method2{
 method3();
}

method3(){
 //wrote mock here and it worked.
}

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2013-01-12
    • 2018-10-27
    • 2017-07-23
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多