How to mock AuthenticationClient.clientCredentialsGrant()

How can I mock this call for unit tests?

In my sources I have something like:

import {AuthenticationClient} from 'auth0'

const auth = new AuthenticationClient({domain: 'foo', clientId: 'bar', clientSecret: 'bar'})
const {access_token} = await auth.clientCredentialsGrant({audience: 'hello'})

In tests I’m trying to mock this:

import {createSandbox} from 'sinon'
import {AuthenticationClient} from 'auth0'

const sandbox = createSandbox()
sandbox.stub(AuthenticationClient.prototype, 'clientCredentialsGrant').resolves({access_token: 'token'})

Except that doesn’t work because clientCredentialsGrant isn’t a function off the prototype, it’s not present on the prototype.

1 Like

Hi @levk80,

The Client Credentials Grant is intended to be used to generate access tokens on behalf of an application for authorization to an API or other backend service. Typically, the Client Credentials Grant should not be used in a Single Page Application (SPA) scenario as it requires that the client secret is hard-coded into the application source.

If you are wishing to use the Client Credentials Grant to generate an access token for Unit Testing and to run Utilities, the best approach is to create a machine to machine application for this purpose and specify the appropriate audience for the API you are requesting a token for.

If you attempting to generate a token to mimic a user authenticating with your SPA, I would recommend one of the other grant types such as Resource Owner Password.

I hope this helps! Please let me know if you have any further questions.

This is not a single page application, it’s a command line tool running in Nodejs. It gets a token from client and secret. I’m trying to write unit tests for it. Are you saying I should create a different client/secret just for unit testing and check those values into my sources? Is there another way without doing that?

@levk80 No, in that case you can use your client and secret, since the system authenticates and authorizes the app rather than a user. For this scenario, it is ok to use the Client Credentials Flow (defined in OAuth 2.0 RFC 6749, section 4.4), in which they pass along their Client ID and Client Secret to authenticate themselves and get a token. For testing you just need to make sure to specify the appropriate audience for the API you are requesting the token for.

If you created an API in Auth0, you would pass the unique identifier for the API. Auth0 Dashboard > APIs > Settings > Identifier.