Reputation: 1120
I want to start a server and run tests on its API with Jasmine.
For that I want to make sure that the server is setup and running before jasmine runs its tests.
Also I have a lot of tests, and I split them into mutliple files.
I dont want to particularly start the server in the beforeAll hook of each test file, as it leads to conflicts on the port the server is running.
I thought of 2 theoretical Solutions that I dont know how to do with Jasmine.
Additional Info: Im in a node.js environment running a express-server and am testing its api (each route gets its test file)
Upvotes: 2
Views: 1673
Reputation: 102457
You can use the helpers
configuration. The files in the helpers directory will be executed before running all the tests. For example:
Project structure:
.
├── .babelrc
├── .editorconfig
├── .gitignore
├── .nycrc
├── .prettierrc
├── LICENSE
├── README.md
├── jasmine.json
├── package-lock.json
├── package.json
└── src
├── helpers
│ ├── console-reporter.js
│ ├── fake-server-setup.js
│ └── jsdom.js
└── stackoverflow
├── 60138152
├── 61121812
├── 61277026
├── 61643544
├── 61985831
└── 62172073
fake-server-setup.js
:
const express = require('express');
beforeAll((done) => {
const app = express();
global.app = app;
const port = 3000;
app.get('/api', (req, res) => {
res.sendStatus(200);
});
app.listen(port, () => {
done();
console.log('server is listening on port:' + port);
});
});
We store the app
variable which we will use in each test file to the global
variable.
a.test.js
:
const supertest = require('supertest');
describe('62172073 - a', () => {
it('should pass', () => {
return supertest(global.app).get('/api').expect(200);
});
});
b.test.js
:
const supertest = require('supertest');
describe('62172073 - b', () => {
it('should pass', () => {
return supertest(global.app).get('/api').expect(200);
});
});
jasmine.json
:
{
"spec_dir": "src",
"spec_files": ["**/?(*.)+(spec|test).[jt]s?(x)"],
"helpers": ["helpers/**/*.js", "../node_modules/@babel/register/lib/node.js"],
"stopSpecOnExpectationFailure": false,
"random": true
}
Test result:
Executing 2 defined specs...
Running in random order... (seed: 03767)
Test Suites & Specs:
(node:54373) ExperimentalWarning: The fs.promises API is experimental
1. 62172073 - bserver is listening on port:3000
✔ should pass (51ms)
2. 62172073 - a
✔ should pass (5ms)
>> Done!
Summary:
👊 Passed
Suites: 2 of 2
Specs: 2 of 2
Expects: 0 (none executed)
Finished in 0.085 seconds
Upvotes: 2