【发布时间】:2017-03-22 05:30:08
【问题描述】:
我终于要搭乘 ES6 火车了。我使用 ES6 和 Babel 编写了一个小型 Node.js 应用程序进行编译。我正在使用 Mocha 编写测试,据我所知,您现在还不应该使用 ES6。
我正在尝试测试我制作的对象类的一些功能。因此,在 Mocha 中,我正在执行以下操作:
var assert = require('assert');
var Icon = require('../lib/icon');
describe('Icons', function() {
describe('#save()', function() {
it('should return a success message & save the icon', function() {
var icon = new Icon('https://cdn4.iconfinder.com/data/icons/social-media-2070/140/_whatsapp-128.png', 'icon-test');
var result = Icon.save();
if(result !== '_whatsapp-128.png saved successfully.') return false;
return fs.existsSync('icon-test/_whatsapp-128.png');
});
});
});
这显然是行不通的:
var icon = new Icon('https://cdn4.iconfinder.com/data/icons/social-media-2070/140/_whatsapp-128.png', 'icon-test');
我不太确定如何使用 ES5 实例化 ES6 对象,然后测试函数。任何帮助将不胜感激。
** 编辑 - 添加图标文件 **
import fs from 'fs';
import https from 'https';
import path from 'path';
class Icon {
constructor(source, destination) {
this.source = source;
this.destination = path.resolve(destination);
}
save() {
console.log(this.source);
// Fetching the icon.
let request = https.get(this.source, (response) => {
// Splitting the file information.
let fileInfo = path.parse(this.source);
// Creating the directory, if it does not already exist.
if(!fs.existsSync(this.destination)) {
fs.mkdirSync(this.destination);
console.log('Destination directory created.\n');
}
// Piping the icon data & saving onto disk.
let iconFile = fs.createWriteStream(this.destination + '/' + fileInfo.base);
response.pipe(iconFile);
return `${fileInfo.base} saved successfully.`;
});
}
}
export default Icon;
【问题讨论】:
-
"这显然行不通" 为什么不呢? ES5 中存在对象,只是
class语法是新的。 -
反对 'ES6' 和 'ES5' 是没有意义的。是JS。请提供有关问题所在的详细信息。错误消息和
../lib/icon的列表会有所帮助。从 ES6 模块中以var Icon = require('../lib/icon')的形式成功导入一个类是不太可能的。 -
错误信息:
Type Error: Icon is not a constructor -
那么它可以被信任——它不是。它可能是 ES6 模块。这是一个对象而不是构造函数。可以记录和检查的是您,而不是其他任何人。该问题没有包含足够的细节并鼓励猜测。
标签: javascript node.js ecmascript-6 mocha.js