我正在定义以下对象,我打算在Mocha测试中使用它来模拟Mongoose模型。我是用Coffeescript写的,因此我无法访问function
关键字:
TodoError = (body) ->
@find = (query, callback) ->
callback 'error', false
@save = (query, callback) ->
callback 'error', false
@init = (body) -> {}
@init body
return @
通过以下方式调用此对象:
TodoError.find {}, (error, todos) -> {}
和
todo = new TodoError body
todo.save (error, todo) -> {}
当我尝试拨打TodoError.find
TypeError: Object function (body) {
this.find = function(query, callback) {
return callback('error', false);
};
this.save = function(query, callback) {
return callback('error', false);
};
this.init = function(body) {
return {};
};
this.init(body);
return this;
} has no method 'find'
我最初使用以下定义为TodoError.find
工作,但我意识到当我来到new TodoError
部分时这不起作用:
TodoError =
find : (query, callback) ->
callback 'error', false
save : (query, callback) ->
callback 'error', false
答案 0 :(得分:0)
好的,我完全忘记了prototype
的所有内容,然后终于找到了通往Coffeescript课程的方法,这个解决方案
class TodoError
# constructor doesn't need to do anything.
constructor: (body) ->
#static methods.
@find: (query, callback) ->
callback 'error', false
@findOne: (query, callback) ->
callback 'error', false
#instance methods.
save: (callback) ->
callback 'error', false
这编译为:
TodoError = (function() {
function TodoError(body) {}
TodoError.find = function(query, callback) {
return callback('error', false);
};
TodoError.findOne = function(query, callback) {
return callback('error', false);
};
TodoError.prototype.save = function(callback) {
return callback('error', false);
};
return TodoError;
})();