[英]Exporting classes with node.js
我有一個名為bob_test.spec.js
的文件中由jasmine-node運行的以下測試代碼
require('./bob');
describe("Bob", function() {
var bob = new Bob();
it("stating something", function() {
var result = bob.hey('Tom-ay-to, tom-aaaah-to.');
expect(result).toEqual('Whatever');
});
});
為了使測試通過,我在一個名為bob.js
的文件中編寫了以下生產代碼
"use strict";
var Bob = function() {
}
Bob.prototype.hey = function (text) {
return "Whatever";
}
module.exports = Bob;
當我運行測試時 - 使用jasmine-node .
- 我得到以下F
Failures:
1) Bob encountered a declaration exception
Message:
ReferenceError: Bob is not defined
Stacktrace:
ReferenceError: Bob is not defined
at null.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:4:17)
at Object.<anonymous> (/Users/matt/Code/oss/deliberate-practice/exercism/javascript/bob/bob_test.spec.js:3:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
Finished in 0.02 seconds
1 test, 1 assertion, 1 failure, 0 skipped
基於我對Javascript的理解,我覺得這應該有效。 node.js對構造函數和模塊導出做了哪些不同的事情阻止了它的工作我認為應該這樣做?
require返回一個對象,你應該將它存儲在某個地方
var Bob = require('./bob');
然后使用此對象
var bobInstance = new Bob();
如果您可以使用ECMAScript 2015,您可以聲明並導出您的類,然后使用解構“導入”您的類,而無需使用對象來獲取構造函數。
在模塊中,您可以像這樣導出
class Person
{
constructor()
{
this.type = "Person";
}
}
class Animal{
constructor()
{
this.type = "Animal";
}
}
module.exports = {
Person,
Animal
};
然后你在哪里使用它們
const { Animal, Person } = require("classes");
const animal = new Animal();
const person = new Person();
這應該可以解決您在通過jasmine-node運行測試時遇到的錯誤:
// Generated by CoffeeScript 1.6.2
(function() {
var Bob;
Bob = (function() {
function Bob() {}
Bob.prototype.hey = function(what) {
return 'Whatever.';
};
return Bob;
})();
module.exports = Bob;
}).call(this);
改善馬文的答案:
"use strict";
var Bob = function() {}
Bob.prototype.hey = function (text) {
return "Whatever";
}
module.exports = new Bob();
// another file
var Bob = require('./bob');
Bob.hey('text');
所以你可以創建一個將它傳遞給module.exports的對象module.exports = new Bob();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.