You can have multiple assertions within the same code block.
In some instances, you can also test more than one outcome.
Something like,
pm.test('Token exists in response', function () {
pm.expect(response.token).to.not.be.oneOf([undefined, null, false, 0]);
pm.expect(response.token).to.not.empty; // covers an empty array
// pm.collectionVariables.set('token', 'bearer ' + response.token);
});
All of the assertions (pm.expect) have to pass before the test (pm.test) block will pass.
The following statement…
Token has to be non empty string but can not throw an error if it is not set at all.
This is bad practice. Your response should return the same response each and every time you send the same data.
Having dynamic tests that check if a certain key is in the response before running the test is brittle and not recommended.
You should test for what you actually want the response to return. Everything else should be a fail, instead of trying to cover the different potential errors in a conditional check.
If the API could potentially return null. Then you need a request that returns null, and the expected result should then be just that. That’s its returned null. It should return null every time you send the same data\request.
If you need a test that covers a missing token, then you need to get the API to return the missing token and then test that.
It’s not a valuable test checking for a response that can never happen. (So you do need a decent conversation with the developer on what the potential responses could be). Ideally this should be part of the API documentation\specification.
Can your API really return a empty array, null, undefined, false or 0 for the token value (as well as no token at all).
This might mean several requests to the same end point to get the test coverage that you need.