Uncertain if this meets your requirements...here is a sample of test using mongoose schema, not the actual mongodb document.
Please confirm if this answer is accurate or suggest any enhancements needed for the test/code.
https://i.sstatic.net/9XQJ8.png
Mocha Test File
var expect = require('chai').expect,
mongooseMock = require('mongoose-mock'),
proxyquire = require('proxyquire'),
sinon = require('sinon'),
chai = require('chai'),
sinonChai = require("sinon-chai");
chai.use(sinonChai);
var AIterator;
describe('model', function() {
beforeEach(function (done) {
AIterator = proxyquire('./ArrayIterator', {'mongoose': mongooseMock});
done();
});
it("should iterate the array",function(done){
setTimeout(done, 15000);
var callback = sinon.spy();
var aIterator=[];
aIterator[0] = AIterator.create({"key":"value1","key2":"value2","keyN":"value3"}, callback);
aIterator[1] = AIterator.create({"key":"value4","key2":"value5","keyN":"value6"}, callback);
aIterator[2] = AIterator.create({"key":"value7","key2":"value8","keyN":"value9"}, callback);
var x=0;
aIterator.forEach(function(element) {
if (element.keyN=="value9") {
element.keyN = "test";
}
}, this);
expect(aIterator[2].keyN).equals("value3");
done();
});
});
Code File
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var arraySchema = new Schema({
key: String,
key2: String,
keyN: String
});
var NewArray = new mongoose.Schema(arraySchema);
NewArray.statics.create = function(params, callback) {
var newUpdate = new NewArray(params);
newUpdate.save(function(err, result) {
callback(err, result);
});
return newUpdate;
};
var ArrayIterator = mongoose.model('Model', NewArray);
module.exports = ArrayIterator;
Alternatively,
another test to handle values in the input array, if that aligns with your intention:
it("should iterate the array",function(done){
setTimeout(done, 15000);
var callback = sinon.spy();
var testArray = ["test", "test1"];
var aIterator = [];
aIterator[0] = AIterator.create({"key": "value1", "key2": "value2", "keyN": "value3"}, callback);
aIterator[1] = AIterator.create({"key": "value4", "key2": "value5", "keyN": "value6"}, callback);
aIterator[2] = AIterator.create({"key": "value7", "key2": "value8", "keyN": "value9"}, callback);
var x = 0;
testArray.forEach(function(element) {
if (element == "test") {
aIterator.forEach(function(element1) {
if (element1.keyN == "value9") {
element1.keyN = element;
}
}, this);
}
}, this);
expect(aIterator[2].keyN).equals("value3");
done();
});