//geoSpacialRepository.js
var geoSpatialRepository = {};
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/repository');
var Schema = mongoose.Schema;
var LocationSchema = new Schema({
type: String,
coordinates: [Number,Number]
});
var Location = mongoose.model('locations', LocationSchema);
var db = mongoose.connection;
geoSpatialRepository.find = function(){
var query = Location.find({}, function(error, data){});
query.exec(function(err, data){
console.log("DATA ************************** ");
console.log (JSON.stringify(data));
});
}
exports.geoSpatialRepository = geoSpatialRepository;
<小时/>
我编写console.log的地方 -> 我希望该变量data
脱离此回调,因为我将在此上下文之外调用此函数geoSpatialRepository.find()
(例如在我的测试用例中)。
//测试文件geoSpacilaRepository.spec.js
var assert = require("assert");
var locationsRepository = require("../geoSpatialRepository.js").geoSpatialRepository;
var chai = require("chai"),
should = chai.should(),
expect = chai.expect,
assert = chai.assert;
describe("finding locations from the database", function(){
//setup
var data = {
"type":"point",
"coordinates":[20,20]
};
before(function(){
locationsRepository.save(data);
});
it("should find the data present in location repository",function(){
//call
var actual = locationsRepository.find();
//assertion
console.log("ACTUAL ********************"+(JSON.stringify(actual)))
expect(actual).deep.equals(data);
});
});
最佳答案
您可能需要像这样重新设计find
geoSpatialRepository.find = function(callBackFunction) {
Location.find({}).exec(callBackFunction);
}
然后您需要从测试用例中调用它,如下所示
it("should find the data present in location repository", function() {
//call
locationsRepository.find(function(error, data) {
console.log("ACTUAL ********************" + (JSON.stringify(actual)))
//assertion
expect(actual).deep.equals(data);
});
});
现在,您作为参数传递给 find
的函数将获取实际的数据
。您可以在该函数中比较数据
和实际
。
关于javascript - 从回调返回一个值或在node.js 中的特定回调之外访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22807073/