accounts-frontend/packages/app/components/user/middlewares/bearerHeaderMiddleware.test.ts

105 lines
3.0 KiB
TypeScript
Raw Normal View History

/* eslint-disable @typescript-eslint/no-non-null-assertion */
import expect from 'app/test/unexpected';
import { State as RootState } from 'app/types';
2016-08-10 00:47:49 +05:30
import bearerHeaderMiddleware from 'app/components/user/middlewares/bearerHeaderMiddleware';
import { MiddlewareRequestOptions } from '../../../services/request/PromiseMiddlewareLayer';
2016-08-10 00:47:49 +05:30
describe('bearerHeaderMiddleware', () => {
2020-05-24 04:38:24 +05:30
const emptyState: RootState = {
user: {},
2016-11-05 15:41:41 +05:30
accounts: {
2020-05-24 04:38:24 +05:30
active: null,
available: [],
},
2020-05-24 04:38:24 +05:30
} as any;
describe('when token available', () => {
const token = 'foo';
const middleware = bearerHeaderMiddleware({
getState: () => ({
...emptyState,
accounts: {
active: 1,
available: [
{
id: 1,
token,
username: 'username',
email: 'email',
refreshToken: null,
},
],
},
}),
} as any);
it('should set Authorization header', async () => {
let data: MiddlewareRequestOptions = {
url: '',
options: {
headers: {},
},
};
data = await middleware.before!(data);
expectBearerHeader(data, token);
});
it('overrides user.token with options.token if available', async () => {
const tokenOverride = 'tokenOverride';
let data: MiddlewareRequestOptions = {
url: '',
options: {
headers: {},
token: tokenOverride,
},
};
data = await middleware.before!(data);
expectBearerHeader(data, tokenOverride);
});
it('disables token if options.token is null', async () => {
const tokenOverride = null;
const data: any = {
options: {
headers: {},
token: tokenOverride,
},
};
const resp = await middleware.before!(data);
expect(resp.options.headers.Authorization, 'to be undefined');
});
2016-11-05 15:41:41 +05:30
});
2020-05-24 04:38:24 +05:30
it('should not set Authorization header if no token', async () => {
const middleware = bearerHeaderMiddleware({
getState: () => ({
...emptyState,
}),
} as any);
const data: MiddlewareRequestOptions = {
url: '',
options: {
headers: {},
},
};
2020-05-24 04:38:24 +05:30
const resp = await middleware.before!(data);
2016-08-10 00:47:49 +05:30
2020-05-24 04:38:24 +05:30
expect(resp.options.headers.Authorization, 'to be undefined');
});
2016-08-10 00:47:49 +05:30
2020-05-24 04:38:24 +05:30
function expectBearerHeader(data: MiddlewareRequestOptions, token: string) {
expect(data.options.headers, 'to satisfy', {
Authorization: `Bearer ${token}`,
});
}
2016-08-10 00:47:49 +05:30
});