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

108 lines
2.5 KiB
TypeScript
Raw Normal View History

import expect from 'app/test/unexpected';
import { RootState } from 'app/reducers';
2016-08-10 00:47:49 +05:30
import bearerHeaderMiddleware from 'app/components/user/middlewares/bearerHeaderMiddleware';
2016-08-10 00:47:49 +05:30
describe('bearerHeaderMiddleware', () => {
2019-12-07 16:58:52 +05:30
const emptyState: RootState = {
user: {},
accounts: {
active: null,
available: [],
},
2019-12-07 16:58:52 +05:30
} as any;
describe('when token available', () => {
const token = 'foo';
const middleware = bearerHeaderMiddleware({
getState: () => ({
...emptyState,
2016-11-05 15:41:41 +05:30
accounts: {
active: 1,
available: [
{
id: 1,
token,
2019-12-07 16:58:52 +05:30
username: 'username',
email: 'email',
refreshToken: null,
},
],
},
}),
2019-12-07 16:58:52 +05:30
} as any);
2019-12-07 16:58:52 +05:30
it('should set Authorization header', async () => {
let data: any = {
options: {
headers: {},
},
};
2019-12-07 16:58:52 +05:30
data = middleware.before && (await middleware.before(data));
2016-11-05 15:41:41 +05:30
expectBearerHeader(data, token);
2016-11-05 15:41:41 +05:30
});
2019-12-07 16:58:52 +05:30
it('overrides user.token with options.token if available', async () => {
const tokenOverride = 'tokenOverride';
2019-12-07 16:58:52 +05:30
let data: any = {
options: {
headers: {},
token: tokenOverride,
},
};
2019-12-07 16:58:52 +05:30
data = middleware.before && (await middleware.before(data));
2016-08-10 00:47:49 +05:30
expectBearerHeader(data, tokenOverride);
});
2016-08-10 00:47:49 +05:30
2019-12-07 16:58:52 +05:30
it('disables token if options.token is null', async () => {
const tokenOverride = null;
2019-12-07 16:58:52 +05:30
const data: any = {
options: {
2019-12-07 16:58:52 +05:30
headers: {} as { [key: string]: any },
token: tokenOverride,
},
};
2016-08-10 00:47:49 +05:30
2019-12-07 16:58:52 +05:30
if (!middleware.before) {
throw new Error('No middleware.before');
}
const resp = await middleware.before(data);
2019-12-07 16:58:52 +05:30
expect(resp.options.headers.Authorization, 'to be undefined');
});
});
2019-12-07 16:58:52 +05:30
it('should not set Authorization header if no token', async () => {
const middleware = bearerHeaderMiddleware({
getState: () => ({
...emptyState,
}),
2019-12-07 16:58:52 +05:30
} as any);
2016-11-05 15:41:41 +05:30
2019-12-07 16:58:52 +05:30
const data: any = {
options: {
2019-12-07 16:58:52 +05:30
headers: {} as { [key: string]: any },
},
};
2019-12-07 16:58:52 +05:30
if (!middleware.before) {
throw new Error('No middleware.before');
}
const resp = await middleware.before(data);
2019-12-07 16:58:52 +05:30
expect(resp.options.headers.Authorization, 'to be undefined');
});
function expectBearerHeader(data, token) {
expect(data.options.headers, 'to satisfy', {
Authorization: `Bearer ${token}`,
});
}
2016-08-10 00:47:49 +05:30
});