To get started, we will simply test that our POST /login endpoint returns with a JWT that contains the user's email as the payload. At the end of the Login attaching a well-formed payload scenario, add the following steps:
And the response string should satisfy the regular expression /^[\w-]+\.[\w-]+\.[\w-.+\/=]*$/
And the JWT payload should have a claim with name sub equal to context.userId
The second step (And the JWT payload should have a claim with name sub equal to context.email) is undefined. To implement it, we must split the token up into three parts, header, payload, and signature; perform base64-decoding on the JWT payload; and then check that its sub property is equal to the expected user ID. Instead of implementing this logic ourselves, however, we can simply use the jsonwebtoken package. So let's add it as a normal dependency, as we will need it for the implementation code as well:
$ yarn add jsonwebtoken
Then, in spec/cucumber/steps/response.js, add the following step definition:
import assert, { AssertionError } from 'assert';
import { decode } from 'jsonwebtoken';
Then(/^the JWT payload should have a claim with name (\w+) equal to context.([\w-]+)$/, function (claimName, contextPath) {
const decodedTokenPayload = decode(this.responsePayload);
if (decodedTokenPayload === null) {
throw new AssertionError();
}
assert.equal(decodedTokenPayload[claimName], objectPath.get(this, contextPath));
});
Run the tests, and these two steps should fail.