如何使用sinon模拟非类成员函数

问题描述 投票:1回答:2

我需要在method2函数中添加mock。但我得到错误

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

class ServiceClass {

  async method1() {

  }

}

async function method2() {}

module.exports = ServiceClass;
javascript testing mocha sinon
2个回答
0
投票

您忘记导出异步方法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');

0
投票

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

async function method2{
 method3();
}

method3(){
 //wrote mock here and it worked.
}
© www.soinside.com 2019 - 2024. All rights reserved.