Class: MockAuthService

Auth.MockAuthService(options)

The MockAuthService class mocks authenticated user-fetching logic and allows for manually setting user data. It is compatible with axios-mock-adapter to wrap its HttpClients so that they can be mocked for testing.

It wraps all methods of the service with Jest mock functions (jest.fn()). This allows test code to assert expectations on all functions of the service while preserving sensible behaviors. For instance, the login/logout methods related to redirecting maintain their real behavior.

This service is NOT suitable for use in an application itself - only tests. It depends on Jest, which should only be a dev dependency of your project. You don't want to pull the entire suite of test dependencies into your application at runtime, probably even in your dev server.

In a test where you would like to mock out API requests - perhaps from a redux-thunk function - you could do the following to set up a MockAuthService for your test:

import { getConfig, mergeConfig } from '@edx/frontend-platform';
import { configure, MockAuthService } from '@edx/frontend-platform/auth';
import MockAdapter from 'axios-mock-adapter';

const mockLoggingService = {
  logInfo: jest.fn(),
  logError: jest.fn(),
};
mergeConfig({
  authenticatedUser: {
    userId: 'abc123',
    username: 'Mock User',
    roles: [],
    administrator: false,
  },
});
configure(MockAuthService, { config: getConfig(), loggingService: mockLoggingService });
const mockAdapter = new MockAdapter(getAuthenticatedHttpClient());
// Mock calls for your tests.  This configuration can be done in any sort of test setup.
mockAdapter.onGet(...);

Also see the initializeMockApp function which also automatically uses mock services for Logging and Analytics.

Constructor

new MockAuthService(options)

Parameters:
Name Type Description
options Object
Properties
Name Type Description
config Object
Properties
Name Type Description
BASE_URL string
LMS_BASE_URL string
LOGIN_URL string
LOGOUT_URL string
REFRESH_ACCESS_TOKEN_ENDPOINT string
ACCESS_TOKEN_COOKIE_NAME string
CSRF_TOKEN_API_PATH string
hydratedAuthenticatedUser Object
authenticatedUser Object
loggingService Object

requires logError and logInfo methods

Implements:
  • AuthService
Source:

Members

ensureAuthenticatedUser

A Jest mock function (jest.fn())

Ensures a user is authenticated. It will redirect to login when not authenticated.

Source:

fetchAuthenticatedUser

A Jest mock function (jest.fn())

Returns the current authenticated user details, as supplied in the authenticatedUser field of the config options. Resolves to null if the user is unauthenticated / the config option has not been set.

Source:

getAuthenticatedHttpClient

A Jest mock function (jest.fn())

Gets the authenticated HTTP client instance, which is an axios client wrapped in MockAdapter from axios-mock-adapter.

Source:

getAuthenticatedUser

A Jest mock function (jest.fn())

If it exists, returns the user data representing the currently authenticated user. If the user is anonymous, returns null.

Source:

getHttpClient

A Jest mock function (jest.fn())

Gets the unauthenticated HTTP client instance, which is an axios client wrapped in MockAdapter from axios-mock-adapter.

Source:

getLoginRedirectUrl

A Jest mock function (jest.fn())

Builds a URL to the login page with a post-login redirect URL attached as a query parameter.

const url = getLoginRedirectUrl('http://localhost/mypage');
console.log(url); // http://localhost/login?next=http%3A%2F%2Flocalhost%2Fmypage
Source:

getLogoutRedirectUrl

A Jest mock function (jest.fn())

Builds a URL to the logout page with a post-logout redirect URL attached as a query parameter.

const url = getLogoutRedirectUrl('http://localhost/mypage');
console.log(url); // http://localhost/logout?next=http%3A%2F%2Flocalhost%2Fmypage
Source:

hydrateAuthenticatedUser

A Jest mock function (jest.fn())

Adds the user data supplied in the hydratedAuthenticatedUser config option into the object returned by getAuthenticatedUser. This emulates the behavior of a real auth service which would make a request to fetch this data prior to merging it in.

console.log(authenticatedUser); // Will be sparse and only contain basic information.
await hydrateAuthenticatedUser()
const authenticatedUser = getAuthenticatedUser();
console.log(authenticatedUser); // Will contain additional user information
Source:

redirectToLogin

A Jest mock function (jest.fn())

Redirects the user to the logout page in the real implementation. Is a no-op here.

Source:

redirectToLogout

A Jest mock function (jest.fn())

Redirects the user to the logout page in the real implementation. Is a no-op here.

Source:

setAuthenticatedUser

A Jest mock function (jest.fn())

Sets the authenticated user to the provided value.

Source:

Methods

applyMiddleware(middleware)

A Jest mock function (jest.fn())

Applies middleware to the axios instances in this service.

Parameters:
Name Type Description
middleware Array

Middleware to apply.

Source: