2022-04-08 17:47:09 +08:00
|
|
|
import { mockUser, mockUserResponse } from '@/__mocks__';
|
2022-02-18 16:25:32 +08:00
|
|
|
import RequestError from '@/errors/RequestError';
|
|
|
|
import * as userQueries from '@/queries/user';
|
2022-02-21 16:42:48 +08:00
|
|
|
import { createContextWithRouteParameters } from '@/utils/test-utils';
|
2022-02-18 16:25:32 +08:00
|
|
|
|
|
|
|
import koaUserInfo from './koa-user-info';
|
|
|
|
|
|
|
|
const findUserByIdSpy = jest.spyOn(userQueries, 'findUserById');
|
|
|
|
|
|
|
|
describe('koaUserInfo middleware', () => {
|
|
|
|
const next = jest.fn();
|
|
|
|
|
|
|
|
it('should set userInfo to the context', async () => {
|
|
|
|
findUserByIdSpy.mockImplementationOnce(async () => Promise.resolve(mockUser));
|
|
|
|
|
|
|
|
const ctx = {
|
|
|
|
...createContextWithRouteParameters(),
|
|
|
|
auth: 'foo',
|
|
|
|
userInfo: { id: '' }, // Bypass the middleware Context type
|
|
|
|
};
|
|
|
|
|
|
|
|
await koaUserInfo()(ctx, next);
|
|
|
|
|
2022-02-21 10:45:31 +08:00
|
|
|
expect(ctx.userInfo).toEqual(mockUserResponse);
|
2022-02-18 16:25:32 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
it('should throw if is not authenticated', async () => {
|
|
|
|
const ctx = {
|
|
|
|
...createContextWithRouteParameters(),
|
|
|
|
auth: 'foo',
|
|
|
|
userInfo: { id: '' }, // Bypass the middleware Context type
|
|
|
|
};
|
|
|
|
|
|
|
|
await expect(koaUserInfo()(ctx, next)).rejects.toMatchError(
|
|
|
|
new RequestError({ code: 'auth.unauthorized', status: 401 })
|
|
|
|
);
|
|
|
|
});
|
|
|
|
});
|