|
| 1 | +import{describe,expect,test}from'vitest'; |
| 2 | +import{store}from'../../src'; |
| 3 | + |
| 4 | +describe('computed with selector',()=>{ |
| 5 | +typeUser={ |
| 6 | +id:string; |
| 7 | +firstName:string; |
| 8 | +lastName:string; |
| 9 | +}; |
| 10 | + |
| 11 | +constusersStore=store({ |
| 12 | +users:[]asUser[], |
| 13 | +}) |
| 14 | +.computed((store)=>({ |
| 15 | +userById:(id:string)=>{ |
| 16 | +returnstore.users.use((users)=>users.find((user)=>user.id===id)); |
| 17 | +}, |
| 18 | +})) |
| 19 | +.computed((store)=>({ |
| 20 | +fullNameById:(id:string)=>{ |
| 21 | +constuser=store.userById.use(id); |
| 22 | +if(!user)returnundefined; |
| 23 | +return`${user.firstName}${user.lastName}`; |
| 24 | +}, |
| 25 | +})); |
| 26 | + |
| 27 | +test('initial computed property value',()=>{ |
| 28 | +conststoreInstance=usersStore.create({ |
| 29 | +users:[ |
| 30 | +{id:'1',firstName:'John',lastName:'Doe'}, |
| 31 | +{id:'2',firstName:'Jane',lastName:'Doe'}, |
| 32 | +], |
| 33 | +}); |
| 34 | + |
| 35 | +expect(storeInstance.userById.get('1')).toEqual({ |
| 36 | +id:'1', |
| 37 | +firstName:'John', |
| 38 | +lastName:'Doe', |
| 39 | +}); |
| 40 | + |
| 41 | +expect(storeInstance.fullNameById.get('1')).toBe('John Doe'); |
| 42 | +}); |
| 43 | +}); |
| 44 | +describe('computed with selector v2',()=>{ |
| 45 | +typeUser={ |
| 46 | +id:string; |
| 47 | +firstName:string; |
| 48 | +lastName:string; |
| 49 | +}; |
| 50 | + |
| 51 | +constusersStore=store({ |
| 52 | +users:[]asUser[], |
| 53 | +}).extend(($)=>({ |
| 54 | +userById:(id:string)=> |
| 55 | +store( |
| 56 | +// the get here is not dynamic, so you have to choose get/use |
| 57 | +$.users.get((users)=>users.find((user)=>user.id===id)) |
| 58 | +).computed((store)=>({ |
| 59 | +fullName:()=>{ |
| 60 | +constuser=store.get(); |
| 61 | +if(!user)returnundefined; |
| 62 | +return`${user.firstName}${user.lastName}`; |
| 63 | +}, |
| 64 | +})), |
| 65 | +})); |
| 66 | + |
| 67 | +test('initial computed property value',()=>{ |
| 68 | +conststoreInstance=usersStore.create({ |
| 69 | +users:[ |
| 70 | +{id:'1',firstName:'John',lastName:'Doe'}, |
| 71 | +{id:'2',firstName:'Jane',lastName:'Doe'}, |
| 72 | +], |
| 73 | +}); |
| 74 | + |
| 75 | +expect(storeInstance.userById('1').get()).toEqual({ |
| 76 | +id:'1', |
| 77 | +firstName:'John', |
| 78 | +lastName:'Doe', |
| 79 | +}); |
| 80 | + |
| 81 | +expect(storeInstance.userById('1').fullName.get()).toBe('John Doe'); |
| 82 | +}); |
| 83 | +}); |