Mocha为原型方法返回undefined

时间:2016-08-19 13:49:59

标签: javascript node.js mocha

我试图对使用原型模式创建对象的Node模块运行一些Mocha测试。代码本身运行得很好,但测试没有。

这是我试图测试的代码:

{{instance.test}}

然后在我的测试代码的相关部分中我实例化一个对象:

"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)方法。相反,尝试调用该函数会给我downloadFile

关于问题所在的任何想法?

THX!

1 个答案:

答案 0 :(得分:0)

这与mocha无关。在定义自己的原型方法之前,需要继承。

来自docs

  

将原型方法从一个构造函数继承到另一个构造函数。构造函数的原型将设置为从superConstructor创建的新对象

util.inherits(FileController, EventEmitter);

FileController.prototype.downloadFile = function() {}

<强> UPD 至于新版本的节点。它现在设置ctor.prototype prototype,因此订单不再重要。

exports.inherits = function(ctor, superCtor) {

  //...Args check

  ctor.super_ = superCtor;
  Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};
相关问题