测试Mongoose Node.JS应用 [英] Testing Mongoose Node.JS app

查看:65
本文介绍了测试Mongoose Node.JS应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Node应用程序的某些部分编写单元测试.我正在将Mongoose用于我的ORM.

I'm trying to write unit tests for parts of my Node app. I'm using Mongoose for my ORM.

我搜索了一堆关于如何用Mongoose和Node进行测试的方法,但没有附带任何内容.解决方案/框架似乎都是全栈式的,或者根本没有提到模拟的东西.

I've searched a bunch for how to do testing with Mongoose and Node but not come with anything. The solutions/frameworks all seem to be full-stack or make no mention of mocking stuff.

有没有一种方法可以模拟我的Mongoose数据库,以便可以在测试中返回静态数据?我宁愿不必设置测试数据库并为每个单元测试填充数据.

Is there a way I can mock my Mongoose DB so I can return static data in my tests? I'd rather not have to set up a test DB and fill it with data for every unit test.

还有其他人遇到过吗?

推荐答案

我通过一些代码结构解决了这个问题.我将所有与猫鼬相关的东西都保存在单独的类中,并使用"save","find","delete"之类的API,并且没有其他类可以直接访问数据库.然后,我只是在依赖数据的测试中模拟那些.

I solved this by structuring my code a little. I'm keeping all my mongoose-related stuff in separate classes with APIs like "save", "find", "delete" and no other class does direct access to the database. Then I simply mock those in tests that rely on data.

我对返回的实际对象做了类似的事情.对于我在猫鼬中拥有的每个模型,我都有一个相应的类将其包装并提供对字段的访问方法.这些也很容易被嘲笑.

I did something similar with the actual objects that are returned. For every model I have in mongoose, I have a corresponding class that wraps it and provides access-methods to fields. Those are also easily mocked.

这篇关于测试Mongoose Node.JS应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆