My mocha test is producing an error message: "Uncaught AssertionError: undefined == 'Ernest'. It seems like the test may be referring to the song instance created at the beginning of the code. I'm unsure about how to resolve this issue.
This API is designed for a MEAN stack application, using mongoose as the ODM.
test.js
it('can save a song', function(done) {
Song.create({ title: 'saveASong' }, function(error, doc) {
assert.ifError(error);
var url = URL_ROOT + '/create/song/saveASong';
superagent.
put(url).
send({
title: 'saveASong',
createdBy: 'Ernest'
}).
end(function(error, res) {
assert.ifError(error);
assert.equal(res.status, status.OK);
Song.findOne({}, function(error, song) {
assert.ifError(error);
assert.equal(song.title, 'saveASong');
assert.equal(song.createdBy, 'Ernest');
done();
});
});
});
});
Custom route:
//PUT (save/update) song from the create view
api.put('/create/song/:title', wagner.invoke(function(Song) {
return function(req, res) {
Song.findOne({ title: req.params.title}, function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
song.save(function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
return res.json({ song: song });
});
});
};
}));
UPDATE: After adding a console.log(res.body) right after "end", the response did not include the "createdBy: Ernest" key-value pair. I attempted to change another key-value pair in the object being sent, but it still didn't persist. There are no errors when I remove the "assert.equal...'Ernest'" line.
Revised version of PUT route:
api.put('/create/song/:title', wagner.invoke(function(Song) {
return function(req, res) {
Song.findOneAndUpdate({ title: req.params.title}, req.body ,{ new: true }, function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
return res.json({ song: song });
});
};
}));