“this”引用在nodeJs中不起作用
"this" reference is not working in nodeJs
我的nodeJs代码中有两个方法,例如
function method1(id,callback){
var data = method2();
callback(null,data);
}
function method2(){
return xxx;
}
module.exports.method1 = method1;
module.exports.method2 = method2;
为了使用 Sinon
和 Mocha
测试函数方法1,我必须stub
方法 方法2。 为此,它需要调用方法 method2 作为
function method1(id,callback){
var data = this.method2();
callback(null,data);
}
为此测试代码
describe('test method method2', function (id) {
var id = 10;
it('Should xxxx xxxx ',sinon.test(function(done){
var stubmethod2 = this.stub(filex,"method2").returns(data);
filex.method1(id,function(err,response){
done();
})
})
})
使用此测试用例通过,但代码停止工作,错误 this.method2 不是一个函数。
有什么方法可以摆脱this
或module.exports
似乎有问题。
如果我错过了任何其他信息,请告诉我。
您没有正确使用 module.exports。
将代码更改为:
export function method1(id,callback){
var data = method2();
callback(null,data);
}
export function method2(){
return xxx;
}
然后:
const MyFuncs = require('path_to_file_with_methods');
在需要方法的地方,像这样调用:
MyFuncs.method1(){}
MyFuncs.method2(){}
模块导出的文档
您还可以通过以下方式使用 module.exports。
module.exports = {
method1: method1,
method2: method2
}
并以同样的方式要求。
编辑:
请注意,如果您的版本支持它,您还可以在导出中加入一些语法糖:
module.exports = {
method1,
method2
}
这适用于一般的对象文字表示法。
使用箭头函数来更正此方法
在您的情况下
function method1(id,callback){
var data = this.method2();
callback(null,data);
}
可以更改为
let method1 = (id,callback)=>{
var data = this.method2();
callback(null,data);
}
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- 幻灯片滚动javascript不起作用
- NodeJS日期格式不起作用
- NodeJS 套接字连接不起作用
- 使用 multer (nodeJs) 上传文件不起作用
- 路由在 Angular 和 nodejs 应用程序中不起作用
- nodejs + archiver,为什么这个zip存档下载器不起作用(存档意外结束)
- NodeJS 断点有时不起作用
- Nodejs的Regex全局匹配不起作用
- Nodejs express静态文件夹对某些文件不起作用
- setTimeout在NodeJS中不起作用
- nodejs 向子进程发送信号不起作用
- 使用gulp-babel ignore编译nodejs应用程序不起作用
- 用变量值而不是文字遍历JSON树,使用NodeJS不起作用
- “this”引用在nodeJs中不起作用
- 简单的if语句在NodeJS中不起作用
- NodeJS HttpGet 方法在 Wiki 上不起作用
- NodeJS 代码不起作用
- 将变量调用到不同的路由在nodejs和express中不起作用