Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - Exporting classes with node.js

I have the following test code that is being ran by jasmine-node in a file called 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');
  });
});

In order to make the test pass, I've written the following production code in a file called bob.js

"use strict";

var Bob = function() {
}

Bob.prototype.hey = function (text) {
  return "Whatever";
}

module.exports = Bob;

When I run the test - using jasmine-node . - I get the following 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

Based on what I understand about Javascript, I feel like this should work. What does node.js do differently with constructor functions and module exports that prevents this from working I like think it should?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

require returns an object, you should store it somewhere

var Bob = require('./bob');

and then use this object

var bobInstance = new Bob();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...