on 2022 Feb 08 9:50 AM
Hi,
I am using cds.test to kick off some mocha tests and this works fine.
The startup of the CDS server.js takes some time however as we added quite some custom logic implementations in the 'served' event. Some of that code is really not relevant for the unit testing.
I was wondering whether there would be a way to 'detect' in the server event that it was started by the cds.test and thus I could avoid running some of my code ?
And second point .. I was expecting the mocha test run to end the server - as per documentation - but it keeps on running. I need to CTRL-C the mocha test process ... is that normal ?
Thanks,
Steven
Request clarification before answering.
You can use NodeJS environment variables, something like that
server.js:
const cds = require("@sap/cds");
cds.on("bootstrap", (app) => {
console.log(process.env.SKIP_WHEN_TEST);
if (process.env.SKIP_WHEN_TEST !== "y") {
console.log("Skiping when running test");
} else {
console.log("Runs when running test");
app.get("/api/test", function(req, res) {
res.json({
flag: false
});
});
}
});
module.exports = cds.server;
and then add define npm script in package.json
...
"scripts": {
"start": "cds run",
"mocha": "SKIP_WHEN_TEST=y npx mocha || echo"
},
...and server.test.js example:
const cds = require("@sap/cds/lib");
const {
expect,
GET,
POST,
PATCH,
DEL,
data
} = cds.test(
"serve",
"--in-memory",
"--project",
`${__dirname}/..`
);
describe("checking that it is running with false", () => {
it("serves custom endpoint", async () => {
const {
headers,
status
} = await GET("/api/test", {});
expect(status).to.equal(200);
});
});Once you run npm run mocha, it will set custom node.js enviroment variable 'SKIP_WHEN_TEST' to y and then you can use it your custom server.js to avoid code to be executed when you are running tests.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Vladimirs,
Thanks for the suggestion.
I understand this is possible and common in node but I don't like the idea of having to depend on setting some external env variable.
It will do for now - thx for reminding me about this option - but I would hope that this should be part of the cds class - eg a method like 'isInTestModus()'
Maybe a better way or suggestion to add this david.kunz2 ?
Kind Regards,
Steven
Hi steven.desaeger ,
Some test runners set NODE_ENV=test automatically, I'm not sure if Mocha does this.
In any way: I would avoid writing test-specific things in your main code base.
What you could do instead: Refactor your complicated logic into a function in another module, then in your test you can just mock that module.
That way, your main code base is clear and your tests efficient.
Best regards,
David
| User | Count |
|---|---|
| 14 | |
| 8 | |
| 6 | |
| 6 | |
| 3 | |
| 3 | |
| 2 | |
| 2 | |
| 2 | |
| 2 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.