使用猫鼬进行单元测试

使用猫鼬进行单元测试

本文介绍了使用猫鼬进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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集合中的实例。

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:


  • 函数是否正确设置内容类型

  • 函数是按日期字段排序

  • 发生错误时函数是否返回403?

  • ...等等

  • 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

我很想知道如何重构我现有的代码来制作它更可单元测试。我尝试过创建第二个被调用的函数,接受响应 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 模型(您的问题)返回 Query 对象的新实例。新的查询实例可以通过原型 exec 方法C>。 (mongoose 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);

这篇关于使用猫鼬进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:56