1+ import { beforeEach , describe , expect , it , vi } from "vitest" ;
2+ import { MemoryCache } from "../../../../src/cache/cache.js" ;
3+
4+ describe ( "MemoryCache" , ( ) => {
5+ let memoryCache ;
6+
7+ beforeEach ( ( ) => {
8+ memoryCache = new MemoryCache ( ) ;
9+ vi . restoreAllMocks ( ) ;
10+ } ) ;
11+
12+ it ( "retorna null quando a chave não existe" , ( ) => {
13+ expect ( memoryCache . get ( "inexistente" ) ) . toBeNull ( ) ;
14+ } ) ;
15+
16+ it ( "salva e recupera um valor dentro do TTL" , ( ) => {
17+ memoryCache . set ( "jobs:react" , [ { titulo : "Dev React" } ] , 1000 ) ;
18+
19+ expect ( memoryCache . get ( "jobs:react" ) ) . toEqual ( [
20+ { titulo : "Dev React" } ,
21+ ] ) ;
22+ } ) ;
23+
24+ it ( "remove e retorna null quando o item expirou" , ( ) => {
25+ const nowSpy = vi . spyOn ( Date , "now" ) ;
26+
27+ nowSpy . mockReturnValueOnce ( 1000 ) ; // set
28+ memoryCache . set ( "jobs:node" , [ { titulo : "Dev Node" } ] , 500 ) ;
29+
30+ nowSpy . mockReturnValueOnce ( 1601 ) ; // get
31+ expect ( memoryCache . get ( "jobs:node" ) ) . toBeNull ( ) ;
32+
33+ expect ( memoryCache . store . has ( "jobs:node" ) ) . toBe ( false ) ;
34+ } ) ;
35+
36+ it ( "deleta uma chave específica" , ( ) => {
37+ memoryCache . set ( "a" , 123 , 1000 ) ;
38+ memoryCache . set ( "b" , 456 , 1000 ) ;
39+
40+ memoryCache . delete ( "a" ) ;
41+
42+ expect ( memoryCache . get ( "a" ) ) . toBeNull ( ) ;
43+ expect ( memoryCache . get ( "b" ) ) . toBe ( 456 ) ;
44+ } ) ;
45+
46+ it ( "limpa todo o cache" , ( ) => {
47+ memoryCache . set ( "a" , 123 , 1000 ) ;
48+ memoryCache . set ( "b" , 456 , 1000 ) ;
49+
50+ memoryCache . clear ( ) ;
51+
52+ expect ( memoryCache . get ( "a" ) ) . toBeNull ( ) ;
53+ expect ( memoryCache . get ( "b" ) ) . toBeNull ( ) ;
54+ } ) ;
55+
56+ it ( "has retorna true quando a chave existe e não expirou" , ( ) => {
57+ memoryCache . set ( "jobs" , [ "vaga 1" ] , 1000 ) ;
58+
59+ expect ( memoryCache . has ( "jobs" ) ) . toBe ( true ) ;
60+ } ) ;
61+
62+ it ( "has retorna false quando a chave não existe" , ( ) => {
63+ expect ( memoryCache . has ( "jobs" ) ) . toBe ( false ) ;
64+ } ) ;
65+
66+ it ( "has retorna false quando a chave expirou" , ( ) => {
67+ const nowSpy = vi . spyOn ( Date , "now" ) ;
68+
69+ nowSpy . mockReturnValueOnce ( 2000 ) ; // set
70+ memoryCache . set ( "jobs" , [ "vaga 1" ] , 100 ) ;
71+
72+ nowSpy . mockReturnValueOnce ( 2201 ) ; // has -> get
73+ expect ( memoryCache . has ( "jobs" ) ) . toBe ( false ) ;
74+ } ) ;
75+ } ) ;
0 commit comments