node.jsauth0express-jwt

How can I mock auth0 authentication for testing?


I am using autho0 and express-jwt in order to authenticate my app users.

Everything is really cool besides the tests. The content that I pass in my API is strictly partitioned by authors. This means you can only access a content if you own it.

I am using req.user.sub (which is provided by jwt if the user is recognized) to set the author of the content that is being passed in my API.

Should I use req.user.name to provide the author? If so, how can I mock the authentication in order to write my tests.


Solution

  • I implemented a simple solution which is a bit rudimentary:

    public static testAuthorName = 'test-author';
    private static getAuthor(req) {
        if (process.env.NODE_ENV === 'test') {
            return MyApiClass.testAuthorName;
        }
        return req.user.sub.split('|')[1];
    }
    

    This way i can just use MyApiClass.testAuthorNamestatically in my tests.