简体   繁体   English

检查是否使用jasmine-node加载了节点模块

[英]Check for node modules being loaded using jasmine-node

So I'm trying to teach myself Jasmine (for node) by working through a tutorial for a Mongoose project, TDD style, writing tests for what each step is supposed to accomplish, then following the actual tutorial, etc. 因此,我试图通过为Mongoose项目设计TDD风格的教程,为每个步骤应该完成的工作编写测试,然后按照实际的教程等,来自学Jasmine(用于节点)。

Of course, my first test is failing. 当然,我的第一个测试失败了。

app.js at this point is two lines: 此时的app.js为两行:

var mongoose = require('mongoose');
console.log(mongoose.version);

This runs fine. 运行良好。 My test however, still fails: 但是我的测试仍然失败:

var app = require('../src/app.js');

describe('App startup', function() {
    it('loads mongoose', function() {
            expect(app.mongoose.version).toBeDefined();
    });
    it('loads jasmine-jquery', function() {
            expect($).toBeDefined();
    });
});

Results in 结果是

Failures:

1) App startup loads mongoose
Message:
 TypeError: Cannot read property 'version' of undefined
Stacktrace:
 TypeError: Cannot read property 'version' of undefined
at null.<anonymous> (/home/jbhelfrich/mongooseBlog/spec/init.spec.js:5:36)

(The jquery test is, of course, expected to fail still at this point.) I've tried it with and without the 'app.' (当然,jQuery测试在这一点上仍然会失败。)我已经在有和没有'app'的情况下进行了尝试。 in the expect clause, but I get the same error--the test suite doesn't see the internals of app.js. 在Expect子句中,但出现相同的错误-测试套件看不到app.js的内部。 But I know it's loading the app.js file correctly, because it's running it--the console.log output appears ahead of the test results. 但是我知道它正在正确加载app.js文件,因为它正在运行它-console.log输出出现在测试结果之前。

So I suspect I've misunderstood something fundamental about scope, or some other rookie mistake, but I'm not sure what that is. 因此,我怀疑我误解了有关范围的一些基本知识或其他一些菜鸟错误,但是我不确定这是什么。

Node.js is structured into modules. Node.js被组织成模块。 If you want aa module's properties to be accessible, that module's properties must be defined in the module.exports variable. 如果要访问模块的属性,则必须在module.exports变量中定义该模块的属性。 This is what an export might look like (note that exports references module.exports ): 这就是导出的样子(请注意, exports引用了module.exports ):

var mongoose = require('mongoose');
console.log(mongoose.version);
exports.mongoose = mongoose;

Then when you've used require() on a file with the code shown above, the variables will be set, where app is equivalent to module.exports in the module that is being loaded: 然后,当您在具有上述代码的文件上使用require()时,将设置变量,其中app等效于正在加载的模块中的module.exports

var app = require('../src/app.js');
console.log(app.mongoose.version);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM