/* eslint-disable unicorn/consistent-function-scoping */ import { isTokenExpired } from './jwt.js'; import * as jwt from 'jsonwebtoken'; import { afterEach, describe, expect, it, vi } from 'vitest'; describe('isTokenExpired', () => { const mockDateNow = (timestamp: number) => { vi.spyOn(Date, 'now').mockReturnValue(timestamp); }; afterEach(() => { vi.restoreAllMocks(); // Сбрасываем все моки после каждого теста }); it('should return true if the token is expired', () => { const token = jwt.sign({}, 'secret', { expiresIn: -10 }); // Токен с истекшим временем mockDateNow(Date.now()); const result = isTokenExpired(token); expect(result).toBe(true); }); it('should return false if the token is not expired', () => { const token = jwt.sign({}, 'secret', { expiresIn: 3_600 }); // Токен с временем жизни 1 час mockDateNow(Date.now()); const result = isTokenExpired(token); expect(result).toBe(false); }); it('should return true if the token will expire within the threshold', () => { const threshold = 300; // 5 минут const token = jwt.sign({}, 'secret', { expiresIn: threshold - 10 }); // Токен с временем жизни чуть меньше порога mockDateNow(Date.now()); const result = isTokenExpired(token, threshold); expect(result).toBe(true); }); it('should return false if the token will expire outside the threshold', () => { const threshold = 300; // 5 минут const token = jwt.sign({}, 'secret', { expiresIn: threshold + 100 }); // Токен с временем жизни больше порога mockDateNow(Date.now()); const result = isTokenExpired(token, threshold); expect(result).toBe(false); }); it('should return true if the token is invalid', () => { const invalidToken = 'invalid.token.string'; const result = isTokenExpired(invalidToken); expect(result).toBe(true); }); it("should throw an error if the token doesn't have an exp field", () => { const token = jwt.sign({ data: 'no exp' }, 'secret', { noTimestamp: true }); // Токен без exp const result = isTokenExpired(token); expect(result).toBe(true); // Ожидается, что вернётся true }); });