Created
June 6, 2022 00:56
-
-
Save andrew8088/19d71c0da41302603b1f25df06774997 to your computer and use it in GitHub Desktop.
Building your own custom jest matchers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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