如何使用 Mocha 和 Chai 测试 Login API NodeJs

Saj*_*aya 2 tdd mocha.js node.js chai

我是测试驱动开发的新手,我想测试我的登录 API,但我似乎无法完全理解如何使用数据库实现测试以及正确的方法是什么?

win*_*ter 5

首先,我也不是这个主题的专家,但我已经使用这种方法有一段时间了。如果有人发现我写的东西是错误的或有些误导,请纠正我。我对批评和意见非常开放。

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

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

npm install supertest --save-dev
Run Code Online (Sandbox Code Playgroud)

我将向您展示一个非常简单的示例,说明如何将它与 mocha 和 chai 一起使用。

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

// 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;
Run Code Online (Sandbox Code Playgroud)

这是登录 API 的示例测试用例:

// 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);
    }); 
});
Run Code Online (Sandbox Code Playgroud)

您可以使用此命令运行它

node_modules/mocha/bin/mocha test/**/*.js
Run Code Online (Sandbox Code Playgroud)

上面的示例假设您将在 /api/v1/login 路径中使用 POST 方法实现登录 API。它还假设您将使用 json 格式接收和响应数据。

示例测试用例的作用是尝试使用以下数据向 /api/v1/login 发送 POST 请求:

{
  username: 'username',
  password: 'password'
}
Run Code Online (Sandbox Code Playgroud)

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

.expect(200)
Run Code Online (Sandbox Code Playgroud)

如果它收到代码不是 200 的响应,则测试将失败。

然后,它期望Content-Type您的响应为application/json。如果期望与现实不符,测试也会失败。

这段代码如下:

.expect(function(response) {
  expect(response.body).not.to.be.empty;
  expect(response.body).to.be.an('object');
})
Run Code Online (Sandbox Code Playgroud)

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

最后,end使用done回调调用函数,以便测试用例可以正常运行。

您可能需要查看 supertest 文档以获取有关如何使用它的更多详细信息。

测试前建立数据库连接

如果您需要在运行所有测试用例之前维护一个数据库连接,这里的想法是:

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

before(function(done) {
    // write database connection code here
    // call done when the connection is established
});
Run Code Online (Sandbox Code Playgroud)

我以前用猫鼬试过,它对我有用。

我希望这有帮助。