I'm new to Node.js, Mongoose, and testing in this environment. I have the following schema declared in a separate file.
Issue = mongoose.model("Issue", {
identifier: String,
date: String,
url: String,
name: String,
thumbnailURL: String
});
Then I have this method which simply returns all of the Issue
instances in the MongoDB collection.
function issues(request, response) {
response.setHeader('Content-Type', 'text/json');
Issue.find().sort('date').exec(function(error, items) {
if (error) {
response.send(403, {"status": "error", "error:": exception});
}
else {
response.send(200, {"issues": items});
}
});
}
I've gotten this far through experimentation, and now I want to test it, but I've run into a problem. How do I go about testing it, without setting up a MongoDB connection, etc. I know that I can set all that stuff up, but that's an integration test. I want to write unit tests to test things like:
- Does the function set the content type correctly
- Does the function sort by the
date
field - Does the function return a 403 when an error occurs?
- ... and so on
I'm curious to see how I could refactor my existing code to make it more unit testable. I've tried maybe creating a second function that's called through, accepting the response
and Item
schema objects as parameters, but it doesn't feel right. Anyone have any better suggestions?
Mongoose
model
(yourIssue
) returns a new instance of theQuery
object. The newquery
instance has access to theexec
method through theprototype
. (mongoose 3.8~)If you want to return an error you can write:
I'm not sure how to test the Content-Type, and I haven't tested this code myself, but I'm happy to help out if it doesn't work. It seems to make sense to me. Basically we just created a callback so we could move the
response.send
out of the actual custom logic, then we can test via that callback. Let me know if it doesn't work or make sense. You can use the links that the other guys posted to prevent having to connect to the db.A good place to start would be:
Using mocha with chaijs and sinonjs in my node code something like this method works for me: