我正在尝试针对使用原型(prototype)模式创建对象的 Node 模块运行一些 Mocha 测试。代码本身运行得很好,但测试却不行。
这是我要测试的代码:
"use strict";
const fs = require("fs"),
request = require("request"),
EventEmitter = require("events").EventEmitter,
util = require("util");
const FileController = function(url, path) {
EventEmitter.call(this);
this.url = url;
this.path = path;
};
FileController.prototype.downloadFile = function() {
if (this.url) {
let file = fs.createWriteStream(this.path);
file.on("finish", function() {
file.close(function() {
this.emit("downloaded");
});
}).on("error", function(err) {
this.handleDownloadError(err, "file-error");
});
// Download the file.
request.get(this.url)
.on("response", function(res) {
if (res.statusCode == 200) {
res.pipe(file);
} else {
fs.unlink(this.path);
}
this.emit("stream", res);
})
.on("error", function(err) {
this.handleDownloadError(err, "request-error");
});
}
};
FileController.prototype.handleDownloadError = function(err, type) {
fs.unlink(this.path);
this.emit(type, err);
};
util.inherits(FileController, EventEmitter);
module.exports = FileController;
然后这是我实例化对象的测试代码的相关部分:
beforeEach(function() {
let url = "http://example.com/logo.png",
path = config.downloadPath + "/cdf42c077fe6037681ae3c003550c2c5";
fileController = new FileController(url, path);
// Outputs 'undefined'.
console.log(fileController.downloadFile);
});
当我调用 new FileController(url, path)
时,它没有附加我附加到原型(prototype)的 downloadFile
方法。相反,尝试调用该函数会给出 fileController.downloadFile 不是函数
。
对于问题出在哪里有什么想法吗?
谢谢!
最佳答案
这与 Mocha 无关。在定义自己的原型(prototype)方法之前,您需要继承。
来自文档
Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.
util.inherits(FileController, EventEmitter);
FileController.prototype.downloadFile = function() {}
UPD
至于新版本的node.现在设置 ctor.prototype
prototype所以顺序不再重要。
exports.inherits = function(ctor, superCtor) {
//...Args check
ctor.super_ = superCtor;
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};
关于javascript - Mocha 返回原型(prototype)方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040745/