georoot georoot - 1 year ago 70
Node.js Question

Proper way to write tests in expressjs

I followed some tutorials online and found out that tests can be written using

and i successfully wrote a small one that i found online

var assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));

Now after this i moved on to testing it with
application. I am not sure on how to write proper tests on it.

Currently i need to manually run the server in one window and run tests in another. Also another setback is the database, every time i run those tests, i need the data to be deleted by default, that is use a separate database for tests and delete the contents after finished.

Because most of the code is restfull api, i am using request to actually make the requests.

Would really appreciate if someone can point me in the right direction so i don't have to manually start the server and clear database just for running test.

The express application is generated using

Answer Source

export your express app, then require it in the test and wrap it in your sender. I'm not that familiar with request, but i believe that chai-http or supertest can do something like that. It will also allow you to run this code through code-coverage tool like NYC.

import { expect } from 'chai';
import request from 'supertest';
import server from '../../server/server';

describe('Test server', () => {
  describe('Fetch component', () => {
    it('Dont find route - return 404', done => {
        .expect(404, done);
    it('Return component', (done) => {
        .expect(200, done);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download