所以我试图为我的REST API(构建在Express和Mongoose之上)编写测试,但遇到了一些麻烦。
我遵循了很多例子和教程,这些例子和教程表明我下面的解决方案应该有效,但事实并非如此——我得到了一个Error: global leak detected: path
造成这种情况的原因似乎是.post( '/api/invoices' )
,但我不明白为什么。
var app = require("../app").app,
request = require("supertest");
describe("Invoice API", function() {
it( "GET /api/invoices should return 200", function (done) {
request(app)
.get( '/api/invoices' )
.expect( 200, done );
});
it( "GET /api/invoices/_wrong_id should return 500", function (done) {
request(app)
.get( '/api/invoices/_wrong_id' )
.expect( 500, done );
});
it( "POST /api/invoices should return 200", function (done) {
request(app)
.post( '/api/invoices' )
.set( 'Content-Type', 'application/json' )
.send( { number: "200" } )
.expect( 200, done );
});
});
发生的情况是,在代码的某个地方,您丢失了var
声明。Mocha足够聪明,可以在你的整个项目中检测到这一点,而不仅仅是你的测试文件。
在中,您可能正在执行以下操作:
path = require('path');
而不是
var path = require('path');
或者甚至。。。
var fs = require('fs') //<--- notice the missing comma
path = require('path');
当您不声明变量时,它们会附加到全局作用域。在Node.js中,这是global
,而在浏览器中,它是window
。