0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-13 21:30:30 -05:00
logto/packages/core/src/middleware/koa-user-info.test.ts
simeng-li 9c3f017704
test(core): add more middleware tests [2 of 2] (#247)
* test(core): add more middleware tests

add more middleware tests

* fix(ut): fix koaUserInfo ut

fix koaUserInfo ut

* fix(ut): fix ut

fix ut

* fix(ut): revert chagnes

revert changes

* fix(ut): fix ut fail after schema update bug

fix ut fail after schema update bug
2022-02-18 16:25:32 +08:00

55 lines
1.5 KiB
TypeScript

import { User, userInfoSelectFields } from '@logto/schemas';
import pick from 'lodash.pick';
import RequestError from '@/errors/RequestError';
import * as userQueries from '@/queries/user';
import { createContextWithRouteParameters } from '@/utils/test-utils';
import koaUserInfo from './koa-user-info';
const findUserByIdSpy = jest.spyOn(userQueries, 'findUserById');
const mockUser: User = {
id: 'foo',
username: 'foo',
primaryEmail: 'foo@logto.io',
primaryPhone: '111111',
roleNames: ['admin'],
passwordEncrypted: null,
passwordEncryptionMethod: null,
passwordEncryptionSalt: null,
name: null,
avatar: null,
identities: {},
customData: {},
};
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);
expect(ctx.userInfo).toEqual(pick(mockUser, ...userInfoSelectFields));
});
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 })
);
});
});