Skip to content

Instantly share code, notes, and snippets.

@andrew8088
Created June 6, 2022 00:56
Show Gist options
  • Save andrew8088/19d71c0da41302603b1f25df06774997 to your computer and use it in GitHub Desktop.
Save andrew8088/19d71c0da41302603b1f25df06774997 to your computer and use it in GitHub Desktop.
Building your own custom jest matchers
import * as api from './api';
const TOKEN_REGEX = /^app-0.\d+$/;
expect.extend({
toBeValidSession(session: api.Session, userId: string, expectedTTL: number) {
const messages: string[] = [];
const validToken = TOKEN_REGEX.test(session.token);
if (!validToken) messages.push('invalid token');
const validTtl = session.ttl === expectedTTL;
if (!validTtl) messages.push('invalid TTL');
const validUserId = session.userId === userId;
if (!validUserId) messages.push('invalid userId');
const pass = validToken && validTtl && validUserId;
return {
pass,
message: () => `expected input ${pass ? 'not ' : ''}to be a valid session (${messages.join(', ')})`
};
}
});
interface CustomMatchers<R = unknown> {
toBeValidSession(userId: string, expectedTTL: number): R;
}
declare global {
namespace jest {
interface Expect extends CustomMatchers {}
interface Matchers<R> extends CustomMatchers<R> {}
interface InverseAsymmetricMatchers extends CustomMatchers {}
}
}
describe('getSession', () => {
it("returns a valid session for users", () =>{
const userId = "user1";
const session = api.getSession(userId, 'user');
expect(session).toBeValidSession(userId, 60);
});
it("returns a valid session for admins", () =>{
const userId = "user1";
const session = api.getSession(userId, 'admin');
expect(session).not.toBeValidSession(userId, 16);
});
});
export type Session = {
token: string;
ttl: number;
userId: string;
}
export function getSession(userId: string, role: 'user' | 'admin'): Session {
return {
token: `app-${Math.random()}`,
ttl: role === 'admin' ? 15 : 60,
userId,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment