I have an NodeJS Express application which I want to unit test which uses cookies. So I want to use a beforeEach or before to create the Cookie.
Code which works without any problem (but without the before method):
import * as chai from 'chai';
import { expect } from 'chai'
import chaiHttp = require('chai-http');
import { app } from '../../server';
describe('Relaties', () => {
describe('Ophalen alle relaties met: GET /api/ehrm-klantnr/relatie', () => {
it('should get alle relaties', (done) => {
let agent = chai.request.agent(app)
agent
.put('/api/ehrm-klantnr/medewerker/login')
.send({ email: 'admin@sfgtest.com', wachtwoord: '<secret>' })
.then(function (res) {
expect(res).to.have.cookie('SESSIONID');
// The `agent` now has the sessionid cookie saved, and will send it
// back to the server in the next request:
return agent.get('/api/ehrm-klantnr/relatie')
.set('meta','1')
.then(function (res) {
expect(res).to.have.status(200);
expect(res.body.data[0].vestiging).to.equal('Slib Hoofdkantoor');
done();
});
});
});
});
});
What does not run is this:
import * as chai from 'chai';
import { expect } from 'chai'
import chaiHttp = require('chai-http');
import { app } from '../../server';
describe('Relaties', () => {
let agent = chai.request.agent(app);
describe('First this one', function () {
beforeEach(function () {
console.log('outer describe - beforeEach');
agent
.put('/api/ehrm-klantnr/medewerker/login')
.send({ email: 'admin@sfgtest.com', wachtwoord: '<secret>' })
.then(function (res) {
expect(res).to.have.cookie('SESSIONID');
});
});
});
describe('Ophalen alle relaties met: GET /api/ehrm-klantnr/relatie', () => {
it('should get alle relaties', (done) => {
return agent.get('/api/ehrm-klantnr/relatie')
.set('meta', '1')
.then(function (res) {
expect(res).to.have.status(200);
expect(res.body.data[0].vestiging).to.equal('Slib Hoofdkantoor');
done();
});
});
});
});
It is completely ignoring my before or beforeEach (both methods don't work). Maybe chai-http does not have before or beforeEach support ? What am I doing wrong ?
After restructuring.
describe('Relaties', () => {
const agent = chai.request.agent(app);
beforeEach(function (done) {
console.log('outer describe - beforeEach');
agent
.put('/api/ehrm-klantnr/medewerker/login')
.send({ email: 'admin@sfgtest.com', wachtwoord: '<secret>' })
.then(function (res) {
expect(res).to.have.cookie('SESSIONID');
done();
});
});
describe('Ophalen alle relaties met: GET /api/ehrm-klantnr/relatie', () => {
it('should get alle relaties', (done) => {
return agent.get('/api/ehrm-klantnr/relatie')
.set('meta', '1')
.then(function (res) {
expect(res).to.have.status(200);
expect(res).to.be.an('object');
expect(res.body.data).to.be.an('array');
expect(res.body.data[0]).to.be.an('object');
expect(res.body.data[0].id).to.equal(1);
done();
});
});
});
});
I still get errors about the promise.