mat*_*tr- 34 javascript node.js jasmine jasmine-node
我有一个由jasmine-node在一个名为的文件中运行的以下测试代码 bob_test.spec.js
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');
});
});
Run Code Online (Sandbox Code Playgroud)
为了使测试通过,我在一个名为的文件中编写了以下生产代码 bob.js
"use strict";
var Bob = function() {
}
Bob.prototype.hey = function (text) {
return "Whatever";
}
module.exports = Bob;
Run Code Online (Sandbox Code Playgroud)
当我运行测试 - 使用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
Run Code Online (Sandbox Code Playgroud)
基于我对Javascript的理解,我觉得这应该有效.node.js对构造函数和模块导出的作用有何不同,这会阻止它工作我认为应该这样做?
mrv*_*rvn 54
require返回一个对象,你应该将它存储在某个地方
var Bob = require('./bob');
Run Code Online (Sandbox Code Playgroud)
然后使用此对象
var bobInstance = new Bob();
Run Code Online (Sandbox Code Playgroud)
Jon*_*del 10
如果您可以使用 ECMAScript 2015,您可以声明和导出您的类,然后使用解构“导入”您的类,而无需使用对象来访问构造函数。
在你这样导出的模块中
class Person
{
constructor()
{
this.type = "Person";
}
}
class Animal{
constructor()
{
this.type = "Animal";
}
}
module.exports = {
Person,
Animal
};
Run Code Online (Sandbox Code Playgroud)
那么你在哪里使用它们
const { Animal, Person } = require("classes");
const animal = new Animal();
const person = new Person();
Run Code Online (Sandbox Code Playgroud)