通过Restify使用测试数据库 [英] Using a testing database with Restify

查看:145
本文介绍了通过Restify使用测试数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 Restify 服务器,并开始使用自己的JSONclient通过Mocha测试其功能.

I created a simple Restify server, and started testing its functionality through Mocha using its own JSONclient.

使用单元测试功能时,可以设置一个指示测试设置的ENV变量,并连接到相应的mongodb数据库.

When Unit Testing functionality, it's possible to set an ENV var indicating a testing setup, and connect to the according mongodb database.

但是,显然,当您使用JSONClient时,请测试已连接的正在运行的" API服务器.

However, when using the JSONClient you, obviously, test the 'running' API server, which is already connected.

有没有办法通过切断数据库连接以不覆盖开发数据库的方式通过客户端进行端到端测试API功能?

Is there any way to end-to-end test API functionality through the client by swithing database-connections as to not overwrite the development database?

我想我可以按照"switchDataConnection"的方式向api添加一个方法,该方法可以切换到测试数据库,但是感觉很脏又黑.

I suppose I could add a method to the api along the lines of "switchDataConnection" which would switch to the testing database, but that feels dirty and hacky.

推荐答案

一种对我有用的方法是env.js文件和config.js文件.

An approach that worked for me was an env.js file and a config.js file.

config.js(确实是从config-dev.jsconfig-prod.js复制的)中,我放置了所有配置设置.目录路径信息和数据库设置之类的东西.

In config.js (really copied from config-dev.js and config-prod.js) I put all my configuration settings. Things like directory path information and database settings.

例如,这是我的开发数据库连接(我正在使用knexjs包):

For example, this is my dev DB connection (I'm using the knexjs package):

var knex = {
  client : 'mysql',
  connection : {
    host : '127.0.0.1',
    user : 'root',
    password : 'pass',
    database : 'testdev',
    charset : 'utf8'
  }
};

在生产配置中,我只是定义了一个不同的连接.

In my production config, I simply have a different connection defined.

然后,在env.js中,我需要config.js文件来加载适当的设置.在我的单元测试中,我可以为开发加载env.js,而在app.js中可以为生产加载.

Then, in env.js, I required the config.js file to load the appropriate settings. In my unit tests, I can load the env.js for dev, and in app.js I can load for production.

有道理吗?但是,您走在正确的道路上,可以对两个不同的DB进行相同的代码测试.

Make sense? You are on the right path though, it is possible to have the same code testing against two different DBs.

评论中的编辑:建议您建立一个测试环境,以便您可以在其他端口上启动自己的API服务器,然后在该环境下运行测试(当然可以连接到测试数据库.

EDIT from comments: I would suggest setting up a test environment where you can start your own API server on a different port, and then run your tests off that (which of course would connect to a test DB).

这篇关于通过Restify使用测试数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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