سؤال

//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;

The place where I have written console.log -> I want that variable data out of this callback as I will call this function geoSpatialRepository.find() outside this context (for instance n my test case).


//TestFile 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);
    });

});
هل كانت مفيدة؟

المحلول

You might have to redesign the find like this

geoSpatialRepository.find = function(callBackFunction) {
    Location.find({}).exec(callBackFunction);
}

And then you need to invoke it, from the test case, like this

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);
    });
});

Now, the function you pass as a parameter to find will get the actual data. You can compare the data and actual in that function.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top