Adrià Vilanova MartÃnez | ab4c80e | 2024-05-04 19:53:33 +0200 | [diff] [blame^] | 1 | import Script, { |
| 2 | ScriptEnvironment, |
| 3 | ScriptPage, |
| 4 | ScriptRunPhase, |
| 5 | } from './Script'; |
| 6 | import { beforeEach, expect, it, jest } from '@jest/globals'; |
| 7 | import ScriptRunner from './ScriptRunner'; |
| 8 | |
| 9 | interface FakeScriptOptions { |
| 10 | id: string; |
| 11 | priority: number; |
| 12 | } |
| 13 | |
| 14 | class FakeScript extends Script { |
| 15 | id: string; |
| 16 | priority: number; |
| 17 | page: ScriptPage.CommunityConsole; |
| 18 | environment: ScriptEnvironment.ContentScript; |
| 19 | runPhase: ScriptRunPhase.Main; |
| 20 | |
| 21 | constructor(options: FakeScriptOptions) { |
| 22 | super(); |
| 23 | this.id = options.id; |
| 24 | this.priority = options.priority; |
| 25 | } |
| 26 | |
| 27 | execute() {} |
| 28 | } |
| 29 | |
| 30 | const fakeScriptMock = jest |
| 31 | .spyOn(FakeScript.prototype, 'execute') |
| 32 | .mockImplementation(function() { |
| 33 | return (this as FakeScript).id; |
| 34 | }); |
| 35 | |
| 36 | beforeEach(() => { |
| 37 | jest.clearAllMocks(); |
| 38 | }); |
| 39 | |
| 40 | it('scripts run in the correct order based on priority', () => { |
| 41 | const scriptsConfig = [ |
| 42 | { |
| 43 | script: new FakeScript({ |
| 44 | id: '1', |
| 45 | priority: 1, |
| 46 | }), |
| 47 | expectedRunPosition: 2, |
| 48 | }, |
| 49 | { |
| 50 | script: new FakeScript({ |
| 51 | id: '2', |
| 52 | priority: 1000, |
| 53 | }), |
| 54 | expectedRunPosition: 3, |
| 55 | }, |
| 56 | { |
| 57 | script: new FakeScript({ |
| 58 | id: '3', |
| 59 | priority: 0, |
| 60 | }), |
| 61 | expectedRunPosition: 1, |
| 62 | }, |
| 63 | { |
| 64 | script: new FakeScript({ |
| 65 | id: '4', |
| 66 | priority: 2 ** 31, |
| 67 | }), |
| 68 | expectedRunPosition: 4, |
| 69 | }, |
| 70 | ]; |
| 71 | |
| 72 | const scriptRunner = new ScriptRunner(); |
| 73 | scriptRunner.add(...scriptsConfig.map((config) => config.script)); |
| 74 | scriptRunner.run(); |
| 75 | |
| 76 | expect(fakeScriptMock).toHaveBeenCalledTimes(scriptsConfig.length); |
| 77 | for (const config of scriptsConfig) { |
| 78 | expect(fakeScriptMock).toHaveNthReturnedWith( |
| 79 | config.expectedRunPosition, |
| 80 | config.script.id, |
| 81 | ); |
| 82 | } |
| 83 | }); |