如果需要登录,如何在Node.js服务器端使用Mocha Chai测试RESTful CRUD api

How to test RESTful CRUD api with Mocha Chai on Node.js server side if login needed?

本文关键字:Mocha Chai 测试 api CRUD RESTful 服务器端 js 登录 Node 如果      更新时间:2023-09-26

我想测试一个web应用程序服务器端的CRUD逻辑。但是只有登录用户才能访问web应用。

if (res.locals.user){
  //CRUD functions here
} 

我知道如何使用Mocha和Chai来测试这些CRUD功能,而不需要登录检查,但是我如何模拟登录用户来测试它们?用饼干吗?

我一般是这样做的:

var request = require('supertest');
describe('My tests', function(){
    var agent = request.agent(app);
    //before all the tests run, log in
    before(function(done){
        request(app)
        .post('/login')
        .send({
            username: 'a@b.com',
            password: 'password123'
        })
        .end(function (err, res) {
            if (err) { return done(err); }
            agent.saveCookies(res);
            done();
        });
    });
    it('Does something when logged in', function (done){
        var req = request(app).get('/account/something')
        .expect(200);
        //attach the logged in cookies to the agent
        agent.attachCookies(req);
        req.end(done);
        //assertions here
    });
})

首先触发一个登录请求,将cookie保存到代理

然后,在请求中,我想使用经过身份验证的请求。将cookie附加到它。

app是Express应用程序的实例

@Russj,假设:

  • 您正在使用passport-local作为passport认证策略
  • 你使用supertest来模拟你的api调用
  • 你已经有一个导出Express应用程序的文件

那么我将如何测试经过验证的端点:

var request = require('supertest'),
    agent = request.agent();
    mongoose = require('mongoose'),
    // this examples assumes /path/to/your/app exports your Express app
    app = require('/path/to/your/app'), 
    // replace this with the model you use for authentication
    UserModel = mongoose.model('UserModel');
    // this example assumes your user model looks something like the following:
    // 
    //     UserModel = new mongoose.Schema({
    //       username:  String,
    //       password: String
    //     });
describe('testing authenticated end-point', function () {
    var UserModel, testuser;
    before(function (done) {
        // this is just to ensure we have a user to log in for your tests
        UserModel.findOneAndUpdate({ 
            { username: 'testuser' }, 
            { username: 'testuser', password: 'testpassword' }, 
            { upsert: true }, // this will create the user if it doesn't already exist
            function(err, doc) {
                testuser = doc
            }
        });
        // I assume /simulate-login is not an existing route in your app
        app.get('/simulate-login', function(req, res) {
            req.login(testuser); // .login is exposed in req by passport
        });
        // now we simulate login of our testuser and save  the cookies
        request(app)
            .get('/simulate-login')
            .end(function (err, res) {
                    if (err) { return done(err); }
                    // save cookies
                    agent.saveCookies(res);
                    done();
            });
    });
    // clean up after ourselves
    after(function () {
        UserModel.remove({ username: 'testuser' }).exec();
    });
    // now we can test an authenticated end-point as long as we attach the saved cookies
    it('should do whatever...', function (done) {
        var req;
        req = request(app)
            .get('/path/to/route/to/test')
            .expect(200);
        // attach cookies
        agent.attachCookies(req);
        // do your reqeust
        req.end(done);          
    });
});