blob: 1ae8f72cd254b7d9829bc13f9c55f7fbae5a1d34 [file] [log] [blame]
Adrià Vilanova Martínezab4c80e2024-05-04 19:53:33 +02001import Script, {
2 ScriptEnvironment,
3 ScriptPage,
4 ScriptRunPhase,
5} from './Script';
6import { beforeEach, expect, it, jest } from '@jest/globals';
Adrià Vilanova Martínez8b591d92024-10-19 15:55:15 +02007import LegacyScriptRunner from './LegacyScriptRunner';
Adrià Vilanova Martínezab4c80e2024-05-04 19:53:33 +02008
9interface FakeScriptOptions {
10 id: string;
11 priority: number;
12}
13
14class 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
30const fakeScriptMock = jest
31 .spyOn(FakeScript.prototype, 'execute')
32 .mockImplementation(function() {
33 return (this as FakeScript).id;
34 });
35
36beforeEach(() => {
37 jest.clearAllMocks();
38});
39
40it('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
Adrià Vilanova Martínez8b591d92024-10-19 15:55:15 +020072 const scriptRunner = new LegacyScriptRunner();
Adrià Vilanova Martínezab4c80e2024-05-04 19:53:33 +020073 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});