问题描述
我是 Node.js、Mongoose 和在此环境中进行测试的新手.我在单独的文件中声明了以下架构.
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
});
然后我有这个方法,它只返回 MongoDB 集合中的所有 Issue
实例.
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});
}
});
}
我通过实验已经走到了这一步,现在我想测试它,但是我遇到了一个问题.如何在不设置 MongoDB 连接等的情况下进行测试.我知道我可以设置所有这些东西,但这是一个集成测试.我想编写单元测试来测试以下内容:
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:
- 函数是否正确设置了内容类型
- 函数是否按
date
字段排序 - 发生错误时函数是否返回 403?
- ...等等
我很想知道如何重构现有代码以使其更易于单元测试.我尝试过创建第二个调用的函数,接受 response
和 Item
模式对象作为参数,但感觉不对.有人有更好的建议吗?
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
(你的Issue
)返回一个新的Query
对象.新的 query
实例可以通过 prototype
访问 exec
方法.(猫鼬3.8~)
Mongoose model
(your Issue
) returns a new instance of the Query
object. The new query
instance has access to the exec
method through the prototype
. (mongoose 3.8~)
如果你想返回一个错误你可以这样写:
If you want to return an error you can write:
sinon.stub(mongoose.Query.prototype, "exec").yields({ name: "MongoError" }, null);
这篇关于使用 Mongoose 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!