使用node.js导出类

我在文件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');

});

});

为了使测试通过,我在名为的文件中编写了以下生产代码 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();

以上是 使用node.js导出类 的全部内容, 来源链接: utcz.com/qa/417865.html

回到顶部