NodeJs学习笔记(五)---单元测试补充

    今天早上继续研究Mocha,忽然发现一个问题,我的大部分程序都是需要登录验证的,所以需要预先登录之后才能进行下一步测试,就开始在网上找答案,发现没有这种资料,很疑惑,最后发现其实是自己太笨了,因为这个问题在Node中太简单了,解决方案如下

     修改bootstrap.test.js,如下

var Sails = require('sails'),
sails;
var request = require('supertest');
var port = 1447; //测试启动端口
agent = request.agent('http://localhost:'+port); //服务器连接,全局变量

before(function (done) {
	Sails.lift({
		log : {
			level : 'error'
		},
		port:port
	}, function (err, server) {
		sails = server;
		if (err) {
			return done(err);
		} else {//登录
			agent.get('/user/login?login_code=18875282207&user_password=111111')
			.end(function (err, res) {
				if (err)
					return done(err);

				done(err, sails);
			});
		}
	});
});

after(function (done) {
	var done_called = false;
	Sails.lower(function () {
		if (!done_called) {
			done_called = true;
			setTimeout(function () {
				sails.log.debug("inside app.lower, callback not called yet. calling.");
				done();
			}, 1000);

		} else {
			sails.log.debug("inside app.lower, callback already called.");
		}
	});
});

  增加了全局变量agent = request.agent('http://localhost:'+port),这个变量可以在以后发起请求,同时启动sailsjs之后,直接登录,以后测试controllers时,就只需要调用agent.get()或者agent.post()就可以了,前面的controller测试UserController.test.js修改如下:

      

var should = require('should');

describe('UsersController', function () {

	describe('#session()', function () {
		it('should get true', function (done) {
			agent.get('/user/test')
			.end(function (err, results) {
				should(results.res.body.authenticated).be.exactly(true);
				done();
			});
		});
	});
});

  其中/user/test的返回值格式为{authenticated: true},如果已经登录则返回true,否则返回false。 

    运行npm test,结果如下

1 passing (8s)

     很简单就解决了,记录下来备忘吧。

原文地址:https://www.cnblogs.com/stone-fly/p/4535792.html