Best JavaScript code snippet using jest-extended
backend.test.ts
Source:backend.test.ts  
...69        });70        it('rejects if no key is provided', async () => {71            /* eslint-disable @typescript-eslint/ban-ts-comment */72            // @ts-ignore73            expect(Backend.getPublicElections()).toReject();74            // @ts-ignore75            expect(Backend.getPublicElections({ key: 5 })).toReject();76            // @ts-ignore77            expect(Backend.getPublicElections({ key: null })).toReject();78            /* eslint-enable @typescript-eslint/ban-ts-comment */79        });80        it('returns paginated data respecting limit and after', async () => {81            const elections = getHydratedData().elections.map(e => {82                const { owner, ...election } = e;83                return {84                    ...election,85                    owned: owner == Backend.NULL_KEY,86                } as PublicElection87            });88            const defaultResults = elections.slice(0, Backend.DEFAULT_RESULT_LIMIT);89            expect(await (await Backend.getPublicElections({90                key: Backend.NULL_KEY,91                limit: Backend.DEFAULT_RESULT_LIMIT92            })).toArray()).toEqual(defaultResults);93            expect(await (await Backend.getPublicElections({94                key: Backend.NULL_KEY,95                after: null96            })).toArray()).toEqual(defaultResults);97            expect(await (await Backend.getPublicElections({98                key: Backend.NULL_KEY,99                limit: Backend.DEFAULT_RESULT_LIMIT,100                after: null101            })).toArray()).toEqual(defaultResults);102            expect(await (await Backend.getPublicElections({103                key: Backend.NULL_KEY,104                after: elections[0].election_id105            })).toArray()).toEqual(elections.slice(1, Backend.DEFAULT_RESULT_LIMIT + 1));106            expect(await (await Backend.getPublicElections({107                key: Backend.NULL_KEY,108                limit: 1109            })).toArray()).toEqual(elections.slice(0, 1));110            expect(await (await Backend.getPublicElections({111                key: Backend.NULL_KEY,112                limit: 1,113                after: elections[0].election_id114            })).toArray()).toEqual(elections.slice(1, 2));115            expect(await (await Backend.getPublicElections({116                key: Backend.NULL_KEY,117                limit: 3,118                after: elections[1].election_id119            })).toArray()).toEqual(elections.slice(2, 5));120            expect(await (await Backend.getPublicElections({121                key: Backend.NULL_KEY,122                limit: getEnv().MAX_LIMIT,123                after: elections[11].election_id124            })).toArray()).toEqual(elections.slice(12, getEnv().MAX_LIMIT + 12));125            expect(await (await Backend.getPublicElections({126                key: Backend.NULL_KEY,127                after: elections[elections.length - 1].election_id128            })).toArray()).toEqual([]);129            expect(await (await Backend.getPublicElections({130                key: Backend.NULL_KEY,131                after: elections[elections.length - 2].election_id132            })).toArray()).toEqual(elections.slice(-1));133            expect(await (await Backend.getPublicElections({134                key: Backend.NULL_KEY,135                after: new ObjectId()136            })).toArray()).toEqual([]);137        });138        it('rejects on non-positive/too large limit or invalid after', async () => {139            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: getEnv().MAX_LIMIT + 1 })).toReject();140            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: 0 })).toReject();141            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: -1 })).toReject();142            expect(() => Backend.getPublicElections({143                key: Backend.NULL_KEY,144                after: new ObjectId('doesnE!')145            })).toThrow();146            expect(Backend.getPublicElections({147                key: Backend.NULL_KEY,148                // eslint-disable-next-line @typescript-eslint/ban-ts-comment149                // @ts-ignore150                after: 'notAnObjectId!'151            })).toReject();152        });153        it('rejects on strange/bad limit and/or after', async () => {154            /* eslint-disable @typescript-eslint/ban-ts-comment */155            // @ts-ignore156            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: 'lol' })).toReject();157            // @ts-ignore158            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: null })).toReject();159            // @ts-ignore160            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, limit: false })).toReject();161            // @ts-ignore162            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, after: 0 })).toReject();163            // @ts-ignore164            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, after: 100 })).toReject();165            // @ts-ignore166            expect(Backend.getPublicElections({ key: Backend.NULL_KEY, after: false })).toReject();167            /* eslint-enable @typescript-eslint/ban-ts-comment */168        });169    });170    describe('::getPublicElection', () => {171        it('returns only public election data', async () => {172            const election = getHydratedData().elections[0];173            expect(await Backend.getPublicElection({174                electionId: election.election_id,175                key: Backend.NULL_KEY176            })).toEqual<PublicElection>({177                election_id: election.election_id,178                title: election.title,179                description: election.description,180                options: election.options as string[],181                created: election.created,182                opens: election.opens,183                closes: election.closes,184                deleted: election.deleted,185                owned: election.owner == Backend.NULL_KEY186            });187        });188        it('rejects if election_id does not exist', async () => {189            expect(Backend.getPublicElection({ electionId: new ObjectId(), key: Backend.NULL_KEY })).toReject();190            // eslint-disable-next-line @typescript-eslint/ban-ts-comment191            //@ts-ignore192            expect(Backend.getPublicElection({ electionId: 'not a real id', key: Backend.NULL_KEY })).toReject();193        });194    });195    describe('::getInternalElection', () => {196        it('returns internal election data', async () => {197            const elections = getHydratedData().elections;198            expect(await Backend.getInternalElection(elections[0].election_id)).toEqual(elections[0]);199            expect(await Backend.getInternalElection(elections[1].election_id)).toEqual(elections[1]);200            expect(await Backend.getInternalElection(elections[5].election_id)).toEqual(elections[5]);201            expect(await Backend.getInternalElection(elections[elections.length - 1].election_id))202                .toEqual(elections[elections.length - 1]);203        });204        it('rejects if election_id does not exist', async () => {205            expect(Backend.getInternalElection(new ObjectId())).toReject();206        });207    });208    describe('::doesElectionExist', () => {209        it('returns expected result with various elections, some non-existent', async () => {210            const elections = getHydratedData().elections;211            expect(await Backend.doesElectionExist(new ObjectId())).toEqual(false);212            /* eslint-disable @typescript-eslint/ban-ts-comment */213            // @ts-ignore214            expect(Backend.doesElectionExist(null)).toReject();215            // @ts-ignore216            expect(Backend.doesElectionExist(undefined)).toReject();217            /* eslint-enable @typescript-eslint/ban-ts-comment */218            expect(await Backend.doesElectionExist(elections[0].election_id)).toEqual(true);219            expect(await Backend.doesElectionExist(elections[1].election_id)).toEqual(true);220            expect(await Backend.doesElectionExist(elections[5].election_id)).toEqual(true);221            expect(await Backend.doesElectionExist(elections[10].election_id)).toEqual(true);222            expect(await Backend.doesElectionExist(elections[elections.length - 1].election_id)).toEqual(true);223        });224    });225    describe('::upsertElection', () => {226        it('inserts a new election when election_id does not exist', async () => {227            const newElection = {228                title: 'New election',229                description: 'This is a new election',230                opens: Date.now() + 10**6,231                closes: Date.now() + 10**7232            };233            // ? Bad props should be ignored234            const badProps = {235                election_id: new ObjectId(),236                /* eslint-disable @typescript-eslint/ban-ts-comment */237                // @ts-ignore238                _id: new ObjectId(),239                // @ts-ignore240                created: 0,241                //@ ts-ignore242                deleted: false,243                // @ts-ignore244                owner: 'fake-owner-id',245                // @ts-ignore246                fakeprop: 'bad',247                //@ ts-ignore248                options: ['repeated', 'repeated']249                /* eslint-enable @typescript-eslint/ban-ts-comment */250            };251            const results = await Promise.all(Object.entries(badProps).map(([k, v]) => Backend.upsertElection({252                election: { ...newElection, [k]: v } as NewElection,253                key: Backend.NULL_KEY254            }).then(() => true, () => false)));255            expect(results).toEqual([...Array(Object.keys(badProps).length)].map(_ => false));256            const election = await Backend.upsertElection({257                election: newElection,258                key: Backend.NULL_KEY259            });260            const returnedElection = await Backend.getInternalElection(election.election_id || new ObjectId('bad'));261            expect(returnedElection.election_id).not.toEqual(badProps.election_id);262            expect(returnedElection.owner).toEqual(Backend.NULL_KEY);263            expect(returnedElection).toEqual(election);264            expect(Backend.upsertElection({265                election: badProps as unknown as NewElection,266                key: Backend.NULL_KEY267            })).toReject();268        });269        it('does not allow invalid opens/closes times', async () => {270            const newElection: NewElection = {271                title: 'New election',272                description: 'This is a new election',273                options: ['1', '2'],274                opens: Date.now() + 10**6,275                closes: Date.now() + 10**7,276            };277            const { opens, closes, ...badElection } = newElection;278            expect(Backend.upsertElection({279                election: { ...newElection, opens: 100, closes: 200 },280                key: Backend.NULL_KEY281            })).toReject();282            /* eslint-disable @typescript-eslint/ban-ts-comment */283            // @ts-ignore284            expect(Backend.upsertElection({285                election: { ...badElection, opens },286                key: Backend.NULL_KEY287            })).toReject();288            // @ts-ignore289            expect(Backend.upsertElection({290                election: { ...badElection, closes },291                key: Backend.NULL_KEY292            })).toReject();293            /* eslint-enable @typescript-eslint/ban-ts-comment */294            expect(Backend.upsertElection({295                election: { ...badElection, closes: 100, opens },296                key: Backend.NULL_KEY297            })).toReject();298            expect(Backend.upsertElection({299                election: { ...badElection, opens: 100, closes },300                key: Backend.NULL_KEY301            })).toReject();302            expect(Backend.upsertElection({303                election: { ...badElection, opens: closes, closes: opens },304                key: Backend.NULL_KEY305            })).toReject();306        });307        it('updates an existing election when election_id already exists', async () => {308            const newElection: NewElection = {309                title: 'New election',310                description: 'This is a new election',311                options: ['1', '2'],312                opens: Date.now() + 10**6,313                closes: Date.now() + 10**7,314            };315            const election1 = await Backend.upsertElection({ election: newElection, key: Backend.NULL_KEY });316            expect(typeof election1.election_id === 'undefined').toBeFalse();317            const election2 = await Backend.upsertElection({318                electionId: election1.election_id,319                election: {320                    ...newElection,321                    description: '',322                    opens: newElection.opens + 200,323                    closes: newElection.closes + 300,324                }325            });326            // ? Bad props should be ignored327            const badProps = {328                // eslint-disable-next-line @typescript-eslint/ban-ts-comment329                // @ts-ignore330                created: 100,331                opens: newElection.closes,332                closes: newElection.opens,333                _id: new Object(),334                election_id: new Object(),335                extra: 'bad',336                options: ['duplicated', 'duplicated', 'detacilpud']337            };338            const results = await Promise.all(Object.entries(badProps).map(([k, v]) => Backend.upsertElection({339                electionId: election1.election_id,340                election: { ...newElection, [k]: v } as NewElection341            }).then(() => true, () => false)));342            expect(results).toEqual([...Array(Object.keys(badProps).length)].map(_ => false));343            expect(election2.election_id).toEqual(election1.election_id);344            expect(election1.opens).toEqual(newElection.opens);345            expect(election2.opens).toEqual(newElection.opens + 200);346            expect(election2.description).toEqual('');347            const returnedElection = await Backend.getInternalElection(election1.election_id || new ObjectId('bad'));348            expect(returnedElection.election_id).toEqual(election1.election_id);349            /* eslint-disable @typescript-eslint/ban-ts-comment */350            // @ts-ignore351            expect(returnedElection._id).toBeUndefined();352            // @ts-ignore353            expect(returnedElection.extra).toBeUndefined();354            /* eslint-enable @typescript-eslint/ban-ts-comment */355            expect(returnedElection.created).toEqual(election1.created);356            // ? Bad props should be ignored!357            expect(returnedElection.created).not.toEqual(100);358            expect(returnedElection.opens).toEqual(newElection.opens + 200);359            expect(returnedElection.closes).toEqual(newElection.closes + 300);360        });361        it("updating `options` empties the election's voter rankings array", async () => {362            const election_id = getHydratedData().elections.slice(-1)[0].election_id;363            expect(await Backend.getRankings(election_id)).toBeArray();364            await Backend.upsertElection({ electionId: election_id, election: { options: ['@', '#', '&'] }});365            expect(await Backend.getRankings(election_id)).toBeEmpty();366        });367        it('rejects when missing necessary params', async () => {368            /* eslint-disable @typescript-eslint/ban-ts-comment */369            // @ts-ignore370            const newElection00: NewElection = { election_id: 'fake', bad: 'nope' };371            // @ts-ignore372            const newElection0: NewElection = {};373            // @ts-ignore374            const newElection1: NewElection = {375                description: 'This is a new election',376                options: ['1', '2'],377                opens: Date.now() + 10**6,378                closes: Date.now() + 10**7379            };380            // @ts-ignore381            const newElection2: NewElection = {382                title: 'New election',383                description: 'This is a new election',384                closes: Date.now() + 10**7385            };386            // @ts-ignore387            const newElection3: NewElection = {388                title: 'New election',389                opens: Date.now() + 10**6,390            };391            /* eslint-enable @typescript-eslint/ban-ts-comment */392            expect(Backend.upsertElection({ election: newElection1, key: Backend.NULL_KEY })).toReject();393            expect(Backend.upsertElection({ election: newElection2, key: Backend.NULL_KEY })).toReject();394            expect(Backend.upsertElection({ election: newElection3, key: Backend.NULL_KEY })).toReject();395            expect(Backend.upsertElection({ election: newElection0, key: Backend.NULL_KEY })).toReject();396            expect(Backend.upsertElection({ election: newElection00, key: Backend.NULL_KEY })).toReject();397            const election_id = getHydratedData().elections[0].election_id;398            expect(Backend.upsertElection({ election: newElection0, electionId: election_id })).toReject();399            expect(Backend.upsertElection({ election: newElection00, electionId: election_id })).toReject();400        });401        it('does not reject on valid new elections', async () => {402            const newElection1: NewElection = {403                title: 'New election',404                description: 'This is a new election',405                options: ['1', '2'],406                opens: Date.now() + 10**6,407                closes: Date.now() + 10**7,408            };409            const newElection2: NewElection = {410                title: 'New election',411                opens: Date.now() + 10**6,412                closes: Date.now() + 10**7,413            };414            expect(Backend.upsertElection({ election: newElection1, key: Backend.NULL_KEY })).toResolve();415            expect(Backend.upsertElection({ election: newElection2, key: Backend.NULL_KEY })).toResolve();416        });417        it('does not reject on valid election updates', async () => {418            const election_id = getHydratedData().elections.slice(-1)[0].election_id;419            const electionPatch0: PatchElection = { options: undefined };420            const electionPatch1: PatchElection = {};421            const electionPatch2: PatchElection = {422                title: 'New election',423                opens: Date.now() + 10**6,424                closes: Date.now() + 10**7,425            };426            const electionPatch3: PatchElection = {427                options: [],428            };429            const electionPatch4: PatchElection = {430                title: 'faker title',431                options: undefined,432            };433            expect(Backend.upsertElection({ election: electionPatch2, electionId: election_id })).toResolve();434            expect(Backend.upsertElection({ election: electionPatch3, electionId: election_id })).toResolve();435            expect(Backend.upsertElection({ election: electionPatch4, electionId: election_id })).toResolve();436            expect(Backend.upsertElection({ election: electionPatch1, electionId: election_id })).toReject();437            expect(Backend.upsertElection({ election: electionPatch0, electionId: election_id })).toReject();438        });439        it('rejects for new elections when illegal keys provided or required keys missing', async () => {440            const newElection1 = {441                opens: Date.now() + 10**6,442                closes: Date.now() + 10**7,443            } as unknown as NewElection;444            const newElection2 = {445                title: 'My new election!',446                description: 'This is a new election',447                options: ['1', '2'],448                closes: Date.now() + 10**7,449            } as unknown as NewElection;450            const newElection3 = {451                title: 'My new election!',452                opens: Date.now() + 10**6,453            } as unknown as NewElection;454            const newElection4 = {455                title: 'My new election!',456                opens: Date.now() + 10**6,457                closes: Date.now() + 10**7,458                deleted: false459            } as unknown as NewElection;460            const newElection5 = {461                title: 'My new election!',462                opens: Date.now() + 10**6,463                closes: Date.now() + 10**7,464                owned: true465            } as unknown as NewElection;466            const newElection6 = {467                title: 'My new election!',468                opens: Date.now() + 10**6,469                closes: Date.now() + 10**7,470                owner: Backend.NULL_KEY471            } as unknown as NewElection;472            const newElection7 = {473                title: 'My new election!',474                opens: Date.now() + 10**6,475                closes: Date.now() + 10**7,476                blahblahlblah: true,477            } as unknown as NewElection;478            expect(Backend.upsertElection({ election: newElection1, key: Backend.NULL_KEY })).toReject();479            expect(Backend.upsertElection({ election: newElection2, key: Backend.NULL_KEY })).toReject();480            expect(Backend.upsertElection({ election: newElection3, key: Backend.NULL_KEY })).toReject();481            expect(Backend.upsertElection({ election: newElection4, key: Backend.NULL_KEY })).toReject();482            expect(Backend.upsertElection({ election: newElection5, key: Backend.NULL_KEY })).toReject();483            expect(Backend.upsertElection({ election: newElection6, key: Backend.NULL_KEY })).toReject();484            expect(Backend.upsertElection({ election: newElection7, key: Backend.NULL_KEY })).toReject();485        });486        it('rejects for updating elections when illegal keys provided', async () => {487            const election_id = getHydratedData().elections.slice(-1)[0].election_id;488            const patchElection2 = {489                created: 0,490            } as unknown as PatchElection;491            const patchElection3 = {492                owner: Backend.NULL_KEY,493            } as unknown as PatchElection;494            const patchElection4 = {495                options: null,496            } as unknown as PatchElection;497            const patchElection5 = {498                owned: true499            } as unknown as PatchElection;500            const patchElection6 = {501                election_id: new ObjectId(),502            } as unknown as PatchElection;503            expect(Backend.upsertElection({ election: patchElection2, electionId: election_id })).toReject();504            expect(Backend.upsertElection({ election: patchElection3, electionId: election_id })).toReject();505            expect(Backend.upsertElection({ election: patchElection4, electionId: election_id })).toReject();506            expect(Backend.upsertElection({ election: patchElection5, electionId: election_id })).toReject();507            expect(Backend.upsertElection({ election: patchElection6, electionId: election_id })).toReject();508        });509        it('rejects on elections with options.length > MAX_OPTIONS_PER_ELECTION', async () => {510            const election_id = getHydratedData().elections.slice(-1)[0].election_id;511            const newElection: NewElection = {512                title: 'New election',513                description: 'This is a new election',514                options: [...Array(getEnv().MAX_OPTIONS_PER_ELECTION + 1)].map((_, ndx) => ndx.toString()),515                opens: Date.now() + 10**6,516                closes: Date.now() + 10**7,517            };518            expect(Backend.upsertElection({ election: newElection, key: Backend.NULL_KEY })).toReject();519            expect(Backend.upsertElection({ election: newElection, electionId: election_id })).toReject();520        });521        it('rejects if any of the values are the incorrect type (number/string)', async () => {522            const election_id = getHydratedData().elections.slice(-1)[0].election_id;523            const newElection1 = {524                title: null,525                opens: Date.now() + 10**6,526                closes: Date.now() + 10**7,527            } as unknown as InternalElection;528            const newElection2 = {529                title: '',530                opens: null,531                closes: Date.now() + 10**7,532            } as unknown as InternalElection;533            const newElection3 = {534                title: '',535                opens: Date.now() + 10**6,536                closes: '10000',537            } as unknown as InternalElection;538            const newElection4 = {539                title: '',540                opens: Date.now() + 10**6,541                closes: Date.now() + 10**7,542                options: null543            } as unknown as InternalElection;544            const newElection5 = {545                title: '',546                opens: Date.now() + 10**6,547                closes: Date.now() + 10**7,548                options: [1, 2]549            } as unknown as InternalElection;550            const newElection6 = {551                title: '',552                opens: Date.now() + 10**6,553                closes: Date.now() + 10**7,554                options: [true]555            } as unknown as InternalElection;556            const newElection7 = {557                title: '',558                opens: Date.now() + 10**6,559                closes: Date.now() + 10**7,560                options: [undefined]561            } as unknown as InternalElection;562            const newElection8 = {563                title: '',564                opens: Date.now() + 10**6,565                closes: Date.now() + 10**7,566                description: null567            } as unknown as InternalElection;568            const newElection9 = {569                title: '',570                opens: Date.now() + 10**6,571                closes: Date.now() + 10**7,572                description: undefined573            } as unknown as InternalElection;574            const newElection10 = {575                title: undefined,576                opens: Date.now() + 10**6,577                closes: Date.now() + 10**7,578            } as unknown as InternalElection;579            expect(Backend.upsertElection({ election: newElection1, key: Backend.NULL_KEY })).toReject();580            expect(Backend.upsertElection({ election: newElection2, key: Backend.NULL_KEY })).toReject();581            expect(Backend.upsertElection({ election: newElection3, key: Backend.NULL_KEY })).toReject();582            expect(Backend.upsertElection({ election: newElection4, key: Backend.NULL_KEY })).toReject();583            expect(Backend.upsertElection({ election: newElection5, key: Backend.NULL_KEY })).toReject();584            expect(Backend.upsertElection({ election: newElection6, key: Backend.NULL_KEY })).toReject();585            expect(Backend.upsertElection({ election: newElection7, key: Backend.NULL_KEY })).toReject();586            expect(Backend.upsertElection({ election: newElection8, key: Backend.NULL_KEY })).toReject();587            expect(Backend.upsertElection({ election: newElection9, key: Backend.NULL_KEY })).toReject();588            expect(Backend.upsertElection({ election: newElection10, key: Backend.NULL_KEY })).toReject();589            expect(Backend.upsertElection({ election: newElection1, electionId: election_id })).toReject();590            expect(Backend.upsertElection({ election: newElection2, electionId: election_id })).toReject();591            expect(Backend.upsertElection({ election: newElection3, electionId: election_id })).toReject();592            expect(Backend.upsertElection({ election: newElection4, electionId: election_id })).toReject();593            expect(Backend.upsertElection({ election: newElection5, electionId: election_id })).toReject();594            expect(Backend.upsertElection({ election: newElection6, electionId: election_id })).toReject();595            expect(Backend.upsertElection({ election: newElection7, electionId: election_id })).toReject();596            expect(Backend.upsertElection({ election: newElection8, electionId: election_id })).toReject();597            expect(Backend.upsertElection({ election: newElection9, electionId: election_id })).toReject();598            expect(Backend.upsertElection({ election: newElection10, electionId: election_id })).not.toReject();599        });600    });601    describe('::isKeyAuthentic', () => {602        it('returns expected result on valid and invalid keys', async () => {603            expect(Backend.isKeyAuthentic('')).toReject();604            expect(await Backend.isKeyAuthentic('d68d8b5e-b926-4925-ac77-1013e56b8c81')).toEqual(false);605            expect(await Backend.isKeyAuthentic(getHydratedData().keys[0].key)).toEqual(true);606        });607        it('returns false if key is NULL_KEY', async () => {608            expect(await Backend.isKeyAuthentic(Backend.NULL_KEY)).toEqual(false);609        });610    });611    describe('::deleteElection', () => {612        it('soft deletes but does not eliminate election document', async () => {613            const election_id = getHydratedData().elections[0].election_id;614            expect(await Backend.doesElectionExist(election_id)).toEqual(true);615            await Backend.deleteElection(election_id);616            expect(await Backend.doesElectionExist(election_id)).toEqual(true);617            expect((await Backend.getInternalElection(election_id)).deleted).toEqual(true);618        });619    });620    describe('::replaceRankings and ::getRankings', () => {621        it("::replaceRankings replaces an election's rankings data, returned by ::getRankings", async () => {622            const election = getHydratedData().elections[0];623            const oldRankings = await Backend.getRankings(election.election_id);624            const newRankings = [{ voter_id: '1', ranking: election.options }];625            await Backend.replaceRankings({ electionId: election.election_id, rankings: newRankings });626            expect(oldRankings.length > 0).toEqual(true);627            expect(await Backend.getRankings(election.election_id)).toEqual(newRankings);628            await Backend.replaceRankings({ electionId: election.election_id, rankings: oldRankings });629            expect(await Backend.getRankings(election.election_id)).toEqual(oldRankings);630            await Backend.replaceRankings({ electionId: election.election_id, rankings: [] });631            expect(await Backend.getRankings(election.election_id)).toEqual([]);632            const newerRankings = [{ voter_id: '1', ranking: [] }, { voter_id: '2', ranking: [] }];633            await Backend.replaceRankings({ electionId: election.election_id, rankings: newerRankings });634            expect(await Backend.getRankings(election.election_id)).toEqual(newerRankings);635            const newestRankings = [...oldRankings.slice(1)];636            await Backend.replaceRankings({ electionId: election.election_id, rankings: newestRankings });637            expect(await Backend.getRankings(election.election_id)).toEqual(newestRankings);638        });639        it('::replaceRankings and ::getRankings rejects if election_id does not exist', async () => {640            expect(Backend.replaceRankings({ electionId: new ObjectId(), rankings: [] })).toReject();641            expect(Backend.getRankings(new ObjectId())).toReject();642        });643        it('::replaceRankings rejects on illegal options', async () => {644            const election = getHydratedData().elections[0];645            /* eslint-disable @typescript-eslint/ban-ts-comment */646            expect(Backend.replaceRankings({647                electionId: election.election_id,648                // @ts-ignore649                rankings: [1]650            })).toReject();651            expect(Backend.replaceRankings({652                electionId: election.election_id,653                // @ts-ignore654                rankings: [1, 2]655            })).toReject();656            expect(Backend.replaceRankings({657                electionId: election.election_id,658                // @ts-ignore659                rankings: [{}]660            })).toReject();661            expect(Backend.replaceRankings({662                electionId: election.election_id,663                // @ts-ignore664                rankings: [{}, {}]665            })).toReject();666            expect(Backend.replaceRankings({667                electionId: election.election_id,668                // @ts-ignore669                rankings: [{ a: 1 }, { b: 2 }]670            })).toReject();671            expect(Backend.replaceRankings({672                electionId: election.election_id,673                // @ts-ignore674                rankings: [{ voter_id: 1 }]675            })).toReject();676            expect(Backend.replaceRankings({677                electionId: election.election_id,678                // @ts-ignore679                rankings: [{ voter_id: '1' }]680            })).toReject();681            expect(Backend.replaceRankings({682                electionId: election.election_id,683                // @ts-ignore684                rankings: [{ voter_id: '1', ranking: [1] }]685            })).toReject();686            /* eslint-enable @typescript-eslint/ban-ts-comment */687            expect(Backend.replaceRankings({688                electionId: election.election_id,689                rankings: [{ voter_id: '1', ranking: ['1'] }]690            })).toReject();691            expect(Backend.replaceRankings({692                electionId: election.election_id,693                rankings: [{ voter_id: '1', ranking: ['1', '2'] }]694            })).toReject();695            expect(Backend.replaceRankings({696                electionId: election.election_id,697                rankings: [{ voter_id: '1', ranking: [election.options[0], election.options[0]] }]698            })).toReject();699            expect(Backend.replaceRankings({700                electionId: election.election_id,701                rankings: [702                    { voter_id: '1', ranking: [election.options[0]] },703                    { voter_id: '1', ranking: [election.options[0]] }704                ]705            })).toReject();706        });707        it('does not reject on valid rankings but does on invalid rankings', async () => {708            const election = getHydratedData().elections[0];709            const newRankings1: VoterRanking[] = [];710            const newRankings2: VoterRanking[] = [711                { voter_id: 'my-userid1', ranking: election.options },712            ];713            const newRankings3: VoterRanking[] = [714                { voter_id: 'my-userid1', ranking: election.options },715                { voter_id: 'my-userid2', ranking: election.options },716                { voter_id: 'my-userid3', ranking: election.options },717            ];718            expect(Backend.replaceRankings({719                electionId: election.election_id,720                rankings: null as unknown as VoterRanking[]721            })).toReject();722            expect(Backend.replaceRankings({723                electionId: election.election_id,724                rankings: false as unknown as VoterRanking[]725            })).toReject();726            expect(Backend.replaceRankings({727                electionId: election.election_id,728                rankings: newRankings1729            })).toResolve();730            expect(Backend.replaceRankings({731                electionId: election.election_id,732                rankings: newRankings2733            })).toResolve();734            expect(Backend.replaceRankings({735                electionId: election.election_id,736                rankings: newRankings3737            })).toResolve();738        });739        it('rejects on rankings with length > MAX_RANKINGS_PER_ELECTION', async () => {740            const election = getHydratedData().elections[0];741            const newRankings = [...Array(getEnv().MAX_RANKINGS_PER_ELECTION + 1)].map((_, ndx) =>742                ({ voter_id: ndx.toString(), ranking: election.options }));743            expect(Backend.replaceRankings({744                electionId: election.election_id,745                rankings: newRankings746            })).toReject();747        });748        it('rejects on rankings that include non-existent options for the election', async () => {749            expect(Backend.replaceRankings({750                electionId: getHydratedData().elections[0].election_id,751                rankings: [{ voter_id: '5', ranking: ['FAKE'] }]752            })).toReject();753        });754        it('rejects if any of the ids or rankings are not the correct type', async () => {755            const election = getHydratedData().elections[0];756            const newRankings1 = [undefined];757            const newRankings2 = [null];758            const newRankings3 = [[]];759            const newRankings4 = [{}];760            const newRankings5 = [[{}]];761            const newRankings6 = [{ blah: 'blah' }];762            const newRankings7 = [{ voter_id: 'blah' }];763            const newRankings8 = [{ ranking: election.options }];764            const newRankings9 = [{ voter_id: 5, ranking: election.options }];765            const newRankings10 = [{ voter_id: true, ranking: election.options }];766            const newRankings11 = [{ voter_id: 'blah', ranking: true }];767            const newRankings12 = [{ voter_id: undefined, ranking: undefined }];768            const newRankings13 = [{ voter_id: null, ranking: null }];769            const newRankings14 = [{ voter_id: null, ranking: election.options }];770            const newRankings15 = [{ voter_id: undefined, ranking: election.options }];771            const newRankings16 = [{ voter_id: 'blah', ranking: null }];772            const newRankings17 = [{ voter_id: 'blah', ranking: undefined }];773            const newRankings18 = [{ voter_id: 'blah', ranking: [...election.options, undefined] }];774            const newRankings19 = [{ voter_id: 'blah', ranking: [...election.options, null] }];775            const newRankings20 = [{ voter_id: 'blah', ranking: [...election.options, 1] }];776            const newRankings21 = [{ voter_id: 'blah', ranking: [...election.options, ...election.options] }];777            const newRankings22 = [{ voter_id: 'blah', ranking: [...election.options, election.options[0]] }];778            const newRankings23 = [779                { voter_id: 'blah', ranking: election.options },780                { voter_id: 'blah', ranking: election.options }781            ];782            const newRankings24 = [{ voter_id: '', ranking: election.options }];783            /* eslint-disable @typescript-eslint/ban-ts-comment */784            expect(Backend.replaceRankings({785                electionId: election.election_id,786                // @ts-ignore787                rankings: newRankings1788            })).toReject();789            expect(Backend.replaceRankings({790                electionId: election.election_id,791                // @ts-ignore792                rankings: newRankings2793            })).toReject();794            expect(Backend.replaceRankings({795                electionId: election.election_id,796                // @ts-ignore797                rankings: newRankings3798            })).toReject();799            expect(Backend.replaceRankings({800                electionId: election.election_id,801                // @ts-ignore802                rankings: newRankings4803            })).toReject();804            expect(Backend.replaceRankings({805                electionId: election.election_id,806                // @ts-ignore807                rankings: newRankings5808            })).toReject();809            expect(Backend.replaceRankings({810                electionId: election.election_id,811                // @ts-ignore812                rankings: newRankings6813            })).toReject();814            expect(Backend.replaceRankings({815                electionId: election.election_id,816                // @ts-ignore817                rankings: newRankings7818            })).toReject();819            expect(Backend.replaceRankings({820                electionId: election.election_id,821                // @ts-ignore822                rankings: newRankings8823            })).toReject();824            expect(Backend.replaceRankings({825                electionId: election.election_id,826                // @ts-ignore827                rankings: newRankings9828            })).toReject();829            expect(Backend.replaceRankings({830                electionId: election.election_id,831                // @ts-ignore832                rankings: newRankings10833            })).toReject();834            expect(Backend.replaceRankings({835                electionId: election.election_id,836                // @ts-ignore837                rankings: newRankings11838            })).toReject();839            expect(Backend.replaceRankings({840                electionId: election.election_id,841                // @ts-ignore842                rankings: newRankings12843            })).toReject();844            expect(Backend.replaceRankings({845                electionId: election.election_id,846                // @ts-ignore847                rankings: newRankings13848            })).toReject();849            expect(Backend.replaceRankings({850                electionId: election.election_id,851                // @ts-ignore852                rankings: newRankings14853            })).toReject();854            expect(Backend.replaceRankings({855                electionId: election.election_id,856                // @ts-ignore857                rankings: newRankings15858            })).toReject();859            expect(Backend.replaceRankings({860                electionId: election.election_id,861                // @ts-ignore862                rankings: newRankings16863            })).toReject();864            expect(Backend.replaceRankings({865                electionId: election.election_id,866                // @ts-ignore867                rankings: newRankings17868            })).toReject();869            expect(Backend.replaceRankings({870                electionId: election.election_id,871                // @ts-ignore872                rankings: newRankings18873            })).toReject();874            expect(Backend.replaceRankings({875                electionId: election.election_id,876                // @ts-ignore877                rankings: newRankings19878            })).toReject();879            expect(Backend.replaceRankings({880                electionId: election.election_id,881                // @ts-ignore882                rankings: newRankings20883            })).toReject();884            expect(Backend.replaceRankings({885                electionId: election.election_id,886                // @ts-ignore887                rankings: newRankings21888            })).toReject();889            expect(Backend.replaceRankings({890                electionId: election.election_id,891                // @ts-ignore892                rankings: newRankings22893            })).toReject();894            expect(Backend.replaceRankings({895                electionId: election.election_id,896                // @ts-ignore897                rankings: newRankings23898            })).toReject();899            expect(Backend.replaceRankings({900                electionId: election.election_id,901                // @ts-ignore902                rankings: newRankings24903            })).toReject();904            /* eslint-enable @typescript-eslint/ban-ts-comment */905        });906        it('can fetch the empty array inserted when a brand new election is created', async () => {907            const newElection: NewElection = {908                title: 'New election',909                opens: Date.now() + 10**6,910                closes: Date.now() + 10**7,911            };912            const { election_id } = await Backend.upsertElection({ election: newElection, key: Backend.NULL_KEY });913            expect(await Backend.getRankings(election_id)).toEqual([]);914        })915    });916    describe('::addToRequestLog', () => {917        it('adds request to log as expected', async () => {...schema-spec.ts
Source:schema-spec.ts  
...47        if (harness) await harness.shutdown();48    });49    describe('when validating the schema', () => {50        it('should throw an error if no topic is incorrect', async () => {51            await expect(makeTest({ group: 'someGroup' })).toReject();52            await expect(makeTest({ topic: null, group: 'someGroup' })).toReject();53            await expect(makeTest({ topic: 23412341, group: 'someGroup' })).toReject();54        });55        it('should throw an error if no group is incorrect', async () => {56            await expect(makeTest({ topic: 'topic' })).toReject();57            await expect(makeTest({ topic: 'topic', group: 1234123 })).toReject();58            await expect(makeTest({ topic: 'topic', group: ['hello'] })).toReject();59        });60        it('should throw an error if configs are incorrect', async () => {61            await expect(makeTest({ id_field: 1234 })).toReject();62            await expect(makeTest({ compression: 'someother' })).toReject();63            await expect(makeTest({ size: 'someother' })).toReject();64            await expect(makeTest({ offset_reset: -1231 })).toReject();65            await expect(makeTest({ offset_reset: 'hello' })).toReject();66        });67    });...Using AI Code Generation
1const { toReject } = require('jest-extended');2expect.extend({ toReject });3const { toBeRejectedWith } = require('jest-extended');4expect.extend({ toBeRejectedWith });5const { toBeRejected } = require('jest-extended');6expect.extend({ toBeRejected });7const { toBeResolvedWith } = require('jest-extended');8expect.extend({ toBeResolvedWith });9const { toBeResolved } = require('jest-extended');10expect.extend({ toBeResolved });11const { toResolveWith } = require('jest-extended');12expect.extend({ toResolveWith });13const { toResolve } = require('jest-extended');14expect.extend({ toResolve });15const { toBeEmpty } = require('jest-extended');16expect.extend({ toBeEmpty });17const { toBeEmptyString } = require('jest-extended');18expect.extend({ toBeEmptyString });19const { toBeString } = require('jest-extended');20expect.extend({ toBeString });21const { toBeBoolean } = require('jest-extended');22expect.extend({ toBeBoolean });23const { toBeNumber } = require('jest-extended');24expect.extend({ toBeNumber });25const { toBeObject } = require('jest-extended');26expect.extend({ toBeObject });27const { toBeArray } = require('jest-extended');28expect.extend({ toBeArray });29const { toBeFunction } = require('jest-extended');30expect.extend({ toBeFunction });Using AI Code Generation
1expect(promise).toReject();2expect(promise).toReject(/error message/);3expect(promise).toReject(new Error('error message'));4expect(promise).toReject({ message: 'error message' });5expect(promise).toReject({ message: /error message/ });6expect(promise).toReject({ code: 'ENOENT' });7expect(promise).toReject({ code: /ENOENT/ });8expect(promise).toReject({ name: 'Error', message: 'error message' });9expect(promise).toReject({ name: 'Error', message: /error message/ });10expect(promise).toReject({ name: 'Error', code: 'ENOENT' });11expect(promise).toReject({ name: 'Error', code: /ENOENT/ });12expect(promise).toReject({ name: 'Error', code: 'ENOENT', message: 'error message' });13expect(promise).toReject({ name: 'Error', code: 'ENOENT', message: /error message/ });14expect(promise).toReject({ name: 'Error', code: /ENOENT/, message: 'error message' });15expect(promise).toReject({ name: 'Error', code: /ENOENT/, message: /error message/ });16expect(promise).toReject({ name: 'Error', code: /ENOENT/, message: /error message/ });17expect(promise).toReject({ name: 'Error', code: /ENOENT/, message:Using AI Code Generation
1test('the data is peanut butter', async () => {2  expect.assertions(1);3  try {4    await user.getUserName(4);5  } catch (error) {6    expect(error).toReject();7  }8});9module.exports = {10  getUserName: (userId) => {11    return new Promise((resolve, reject) => {12      if (userId === 4) {13        reject(new Error('User with 4 not found.'));14      } else {15        resolve(userId);16      }17    });18  },19};20describe('test toReject method of jest-extended', () => {21  it('should return error message', async () => {22    expect.assertions(1);23    try {24      await user.getUserName(4);25    } catch (error) {26      expect(error).toReject();27    }28  });29});Using AI Code Generation
1const toReject = require('jest-extended').toReject;2const toRejectWith = require('jest-extended').toRejectWith;3const toThrow = require('jest-extended').toThrow;4const toThrowWith = require('jest-extended').toThrowWith;5const toThrowError = require('jest-extended').toThrowError;6const toThrowErrorWith = require('jest-extended').toThrowErrorWith;7const toThrowErrorMatchingSnapshot = require('jest-extended').toThrowErrorMatchingSnapshot;8const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;9const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;10const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;11const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;12const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;13const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;14const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;15const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;16const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingInlineSnapshot;17const toThrowErrorMatchingInlineSnapshot = require('jest-extended').toThrowErrorMatchingUsing AI Code Generation
1expect(Promise.reject(new Error('foo'))).toReject();2expect(Promise.resolve({a: 1})).toResolve();3expect(Promise.resolve({a: 1})).toResolveWith({a: 1});4expect(Promise.reject(new Error('foo'))).toRejectWith(new Error('foo'));5expect({a: 1, b: 2}).toHaveProperty('a');6expect([]).toBeEmpty();7expect(1).toBeOneOf([1, 2, 3]);8expect([]).toBeArray();9expect([1, 2, 3]).toBeArrayOfSize(3);10expect(true).toBeBoolean();11expect(new Date()).toBeDate();12expect([]).toBeEmptyArray();13expect({}).toBeEmptyObject();14expect('').toBeEmptyString();15expect(false).toBeFalse();16expect(() => {}).toBeFunction();17expect(2).toBeGreaterThanOrEqual(1);18expect(new Error()).toBeInstanceOf(Error);19expect(1).toBeInteger();20expect(1).toBeLessThanOrEqual(2);21expect(new Map()).toBeMap();22expect(NUsing AI Code Generation
1const { toReject } = require("jest-extended");2test("should reject", () => {3  return expect(Promise.reject(new Error("foo"))).toReject();4});5const { toReject } = require("jest-extended");6test("should reject with error message", () => {7  return expect(Promise.reject(new Error("foo"))).toReject(8  );9});10const { toReject } = require("jest-extended");11test("should reject with error", () => {12  return expect(Promise.reject(new Error("foo"))).toReject(13    new Error("foo")14  );15});16const { toReject } = require("jest-extended");17test("should reject with error message containing", () => {18  return expect(Promise.reject(new Error("foo"))).toReject(19  );20});21const { toReject } = require("jest-extended");22test("should reject with error containing", () => {23  return expect(Promise.reject(new Error("foo"))).toReject(24    new Error("foo")25  );26});27const { toReject } = require("jest-extended");28test("should reject with error message", () => {29  return expect(Promise.reject("foo")).toReject(30  );31});32const { toReject } = require("jest-extended");33test("should reject with error", () => {34  return expect(Promise.reject("foo")).toReject(35    new Error("foo")36  );37});38const { toReject } = require("jest-extended");39test("should reject with error message containing", () => {40  return expect(Promise.reject("foo")).toReject(41  );42});43const { toReject } = require("jest-extended");44test("should reject withUsing AI Code Generation
1it('should return a promise that rejects with the given error', () => {2    return expect(Promise.reject(new Error('foo'))).toReject();3  });4it('should return a promise that rejects with the given error', async () => {5    await expect(Promise.reject(new Error('foo'))).toReject();6  });7it('should return a promise that rejects with the given error', async () => {8    await expect(Promise.reject(new Error('foo'))).toReject();9  });10it('should return a promise that rejects with the given error', async () => {11    await expect(Promise.reject(new Error('foo'))).toReject();12  });13it('should return a promise that rejects with the given error', async () => {14    await expect(Promise.reject(new Error('foo'))).toReject();15  });16it('should return a promise that rejects with the given error', async () => {17    await expect(Promise.reject(new Error('foo'))).toReject();18  });19it('should return a promise that rejects with the given error', async () => {20    await expect(Promise.reject(new Error('foo'))).toReject();21  });22it('should return a promise that rejects with the given error', async () => {23    await expect(Promise.reject(new Error('foo'))).toReject();24  });Using AI Code Generation
1const { toReject } = require('jest-extended');2describe('Test async code', () => {3    test('test async code', async () => {4        await expect(Promise.reject(new Error('error'))).toReject();5    });6});7    ✓ test async code (3ms)Using AI Code Generation
1test('the data is peanut butter', () => {2  expect(Promise.reject(new Error('error'))).toReject();3});4I am using jest-extended in my project and I am trying to use toReject method of jest-extended to test if a promise is rejected or not. But when I run the test, I get an error saying "TypeError: expect(...).toReject is not a function". I have tried to import jest-extended in the test file and in the setupTest.js file but still, I am getting the same error. What am I doing wrong? I am using jest-extended version 0.11.2 and jest version 24.9.05export const getAlbums = () => {6  return new Promise((resolve, reject) => {7    const request = new XMLHttpRequest();8    request.onload = () => {9      if (request.status === 200) {10        resolve(request.response);11      } else {12        reject(Error(request.statusText));13      }14    };15    request.onerror = () => {16      reject(Error('Network Error'));17    };18    request.send();19  });20};21test('getAlbums should return a list of albums', () => {22  expect(getAlbums()).resolves.toBe('test');23});24TypeError: expect(...).resolves is not a function25export const getAlbums = () => {26  return new Promise((resolve, reject) => {27    const request = new XMLHttpRequest();28    request.onload = () => {29      if (request.status === 200) {30        resolve(request.response);31      } else {32        reject(Error(request.statusText));33      }34    };35    request.onerror = () => {36      reject(Error('Network Error'));Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
