UNPKG

2.77 kBMarkdownView Raw
1
2# Testing Igo Applications
3
4Testing your application is super important. Igo helps to write efficient tests easily.
5
6Igo uses [Mocha](https://mochajs.org/) test framework, and offers more features:
7- Testing controllers layer with [superagent](https://github.com/visionmedia/superagent)
8- Automatic test database reinitialization before first test
9- Test isolation: each test runs in a transaction that is rollbacked
10
11
12## Introduction
13
14All tests run in the `test` environment, which allows you to define specific configuration for your tests.
15
16All the tests must include this Igo Test init instruction:
17```js
18require('igo').dev.test();
19```
20
21This function will initialize the Mocha test suite, and do the following:
22- reinitialize the 'test' database : drop, create, and execute all the `/sql/*.sql` files
23- Flush the cache (Redis)
24- __Begin__ a DB transaction before each test
25- __Rollback__ the DB transaction after each test
26
27
28## How to write a test
29
30Here is a basic test example
31
32```js
33
34require('igo').dev.test();
35
36var assert = require('assert');
37var DateUtils = require('../../app/utils/DateUtils');
38
39describe('utils/DateUtils', function() {
40 describe('startOfDay', function() {
41 it('should return start of day', function() {
42 var d = new Date();
43 var start = DateUtils.startOfDay(d);
44 assert.equal(start.getHours(), 0);
45 assert.equal(start.getMinutes(), 0);
46 assert.equal(start.getSeconds(), 0);
47 });
48 });
49});
50
51```
52
53## Testing the Controller Layer
54
55Here are some basic tests for controllers.
56
57### Test redirection
58```js
59require('igo').dev.test();
60
61var assert = require('assert');
62var agent = require('igo').dev.agent;
63
64describe('controllers/IndexController', function() {
65 describe('/', function() {
66 // redirection test
67 it('should redirect to /foo', function(done) {
68 agent.get('/', function(err, res) {
69 assert.equal(res.statusCode, 302);
70 assert.equal(res.redirectUrl, '/foo');
71 done();
72 });
73 });
74 });
75});
76```
77### Test body in HTML response
78
79The HTML response is set in `res.body`.
80
81```js
82//...
83it('should show form', function(done) {
84 agent.get('/foo', function(err, res) {
85 assert.equal(res.statusCode, 200);
86 assert(res.body.match(/<form /));
87 done();
88 });
89});
90//...
91```
92
93### Test JSON response
94
95The JSON response is set in `res.data`.
96
97```js
98//...
99it('should return user and login', function(done) {
100 User.create({login: 'John'}, function(err, user) {
101 var req = {
102 body: {
103 login: user.login,
104 }
105 };
106 agent.post('/api/login', req, function(err, res) {
107 assert(res.data.id);
108 assert.equal(res.data.login, user.login);
109 assert.equal(res.locals.session.current_user.id, user.id);
110 done();
111 });
112 });
113//...
114```