使用 Mongoose 进行单元测试

编程入门 行业动态 更新时间:2024-10-10 06:21:39
本文介绍了使用 Mongoose 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是 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 进行单元测试

本文发布于:2023-11-16 10:57:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   Mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!