I'm trying to build a test script using node.js. I am utilising assert and using the mocha testing framework for this. A feature of this is to be testing that registering a new user always returns 200. To do this, I've declared a timestamp using the following method:
var currentDate = new Date();
var timestamp = currentDate.getTime();
var testInvitee = {
"username": "name.lastname+11231232" + timestamp + "@company.com"
};
The idea is whenever I run the test the string should be different as the timestamp will change. When running mocha, however, I receive this response:
Testing registration
Register new user:
AssertionError [ERR_ASSERTION]: 403 === 400
+ expected - actual
-200
+400
at Context.it (test.js:596:28)
at <anonymous>
I've done a number of console.log()
calls during the course of the script which revealed that the timestamp
is undefined. See response body below:
Testing as System User.
undefined
Testing candidates
undefined
√ Get candidates (145ms)
//more code
Testing registration
undefined
13) Register new user
I'm not sure as to why the timestamp is undefined in this instance. I'm expecting it to be milliseconds since Jan 1, 1970 as it normally is. Is there anything I've missed out or done incorrectly? Perhaps there is a library I should be using? If it's not the timestamp
causing the problem, I have to assume the problem is deeper in the API but I am certain this is not the case.
EDIT: Here is the code block from the describe
it
blocks in case I've caused a problem in here also:
describe('Testing registration', function () {
before(async () => {
await backend.authenticate();
});
it('Register new user', async () => {
const output = await backend.registerUser()
console.log("", backend.timestamp);
switch (userLevel) {
case "CLIENT_ADMIN":
assert.strictEqual(200, output.statusCode);
break;
case "ADMIN":
assert.strictEqual(200, output.statusCode);
break;
case "GROUP_ADMIN":
assert.strictEqual(200, output.statusCode);
break;
case "HR":
assert.strictEqual(200, output.statusCode);
break;
case "USER":
assert.strictEqual(200, output.statusCode);
break;
default:
console.log("No case match");
break;
}
});
})
The problem, most likely is in the scope.
Your code for declaring timestamp
is correct. But the fact that on the tests the value is undefined
tells us that the test scope does not have access to the scope where you defined the timestamp
.
The easiest check for that would be too add the timestamp
declaration right before it is used in the test.
Or just inline it:
var testInvitee = {
username: "name112233" + new Date().getTime() + "@company.com"
}
Other then that it is hard to tell without the full code. Plus why are you checking backend.timestamp
with the console.log in the test?