I’m working on a couple of tests for a backend created with Express and running with Node. The tests works when I run them separately / individually, but not when I run them together.
npm run test-auth ==> Ok
npm run test-api ==> Ok
npm test ==> Fails
Error message:
1) Authentication
addUser
should register a new user:
TypeError: Cannot read properties of undefined (reading 'execute')
at Context.<anonymous> (file:///home/k/backend/test/test-authentication.mjs:22:26)
at process.processImmediate (node:internal/timers:478:21)
The testfiles looks similar, in terms of app, chai.request.execute etc.:
import { use, expect } from 'chai';
import chaiHttp from 'chai-http';
import { app } from '../src/server.mjs';
const chai = use(chaiHttp);
describe('Authentication', function() {
describe('addUser', function () {
it('should register a new user', function (done) {
const email = `${Math.random().toString(36).substring(7)}@disney.com`;
chai.request.execute(app)
.post('/graphql')
.send({
query: `
mutation {
addUser(email: "${email}", password: "donaldduck") {
email
}
}
`
})
.end((err, res) => {
if (err) {
console.error(err);
}
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.have.property('data');
expect(res.body.data).to.have.property('addUser');
expect(res.body.data.addUser).to.have.property('email', email);
done();
});
});
});
});
My scripts looks like this:
"scripts": {
"test": "NODE_ENV=test mocha 'test/test-*.mjs' --experimental-modules --timeout 5000 --exit",
"test-auth": "NODE_ENV=test mocha test/test-authentication.mjs --experimental-modules --timeout 5000 --exit",
"test-api": "NODE_ENV=test mocha test/test-api.mjs --experimental-modules --timeout 5000 --exit",
"start": "node src/server.mjs"
},
I did try a couple of things, such as adding --flag
to test, change chai.request.execute(app)
to chai.request(app), etc. and am now stuck, at least if I want the tests to be in separate files.