如何使用Mocha和ChaitestingLogin API NodeJs

我是新来的testing驱动开发,我想testing我的loginAPI,但我似乎无法完全理解如何实现与数据库的testing,什么是正确的方法来做到这一点?

首先,我也不是这个话题的专家,但是我一直在使用这个方法很长一段时间。 如果有人发现我写的是错误的或有点误导性的,请纠正我。 我对评论家和意见非常开放。

顾名思义,TDD方法要求你在实现之前编写testing。 基本上,你写testing,看看它的失败,写实现,并重复,直到testing通过。

如果您使用快递,您可能需要使用supertest模块。 他们使用它的方式类似于superagent 。 你可以通过运行来安装它

 npm install supertest --save-dev 

我会告诉你一个非常简单的例子,如何使用它与摩卡和柴。

所以这里是一个快速应用程序的例子:

 // file: app.js const express = require('express'); const app = express(); // your middlewares setup goes here const server = app.listen(8000, () => { console.log('Server is listening on port 8000'); }); module.exports = app; 

这里是loginAPI的示例testing用例:

 // file: test/api.js const request = require('supertest'); const app = require('../app'); const expect = require('chai').expect; describe('Login API', function() { it('Should success if credential is valid', function(done) { request(app) .post('/api/v1/login') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send({ username: 'username', password: 'password' }) .expect(200) .expect('Content-Type', /json/) .expect(function(response) { expect(response.body).not.to.be.empty; expect(response.body).to.be.an('object'); }) .end(done); }); }); 

你可以用这个命令来运行它

 node_modules/mocha/bin/mocha test/**/*.js 

上面的例子假设你将使用POST方法在/ api / v1 / loginpath下实现loginAPI。 它还假定您将接收和使用json格式的数据。

该示例testing用例会尝试使用以下数据向/ api / v1 / login发送POST请求:

 { username: 'username', password: 'password' } 

然后,它期望您的API将响应200个响应代码,如下所示:

 .expect(200) 

如果收到200以外的代码,则testing将失败。

然后,它期望您的响应的Content-Type成为application/json 。 如果期望不符合现实,testing也将失败。

以下代码:

 .expect(function(response) { expect(response.body).not.to.be.empty; expect(response.body).to.be.an('object'); }) 

它检查你的服务器的响应。 如上所示,您可以在函数体内使用chai的expect 。 你可能会注意到超类也提供了expect方法。 但是,同时使用supertest的期望和chai的期望的方式是不同的。

最后,用donecallback函数调用end函数,以便testing用例可以正常运行。

你可能想要检查超级文件,以获得更多关于如何使用它的细节。

testing之前build立数据库连接

如果在运行所有的testing用例之前需要维护一个数据库连接,可以这样做:

test目录中创build另一个文件。 例如, database_helper.js 。 然后,写下面的代码:

 before(function(done) { // write database connection code here // call done when the connection is established }); 

我之前用mongoose试过了,它对我很有用。

我希望有帮助。