summaryrefslogtreecommitdiffstats
path: root/tests/manual/wasm/shared/testrunner.js
blob: da87026b03c271c3f7bf200249727246c62eb258 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

function output(message)
{
    const outputLine = document.createElement('div');
    outputLine.style.fontFamily = 'monospace';
    outputLine.innerText = message;

    document.body.appendChild(outputLine);

    console.log(message);
}

export class TestRunner
{
    #testClassInstance

    constructor(testClassInstance)
    {
        this.#testClassInstance = testClassInstance;
    }

    async run(testCase)
    {
        const prototype = Object.getPrototypeOf(this.#testClassInstance);
        try {
            output(`Running ${testCase}`);
            if (!prototype.hasOwnProperty(testCase))
                throw new Error(`No such testcase ${testCase}`);

            if (prototype.beforeEach) {
                await prototype.beforeEach.apply(this.#testClassInstance);
            }

            await new Promise((resolve, reject) =>
            {
                let rejected = false;
                const timeout = window.setTimeout(() =>
                {
                    rejected = true;
                    reject(new Error('Timeout after 2 seconds'));
                }, 2000);
                prototype[testCase].apply(this.#testClassInstance).then(() =>
                {
                    if (!rejected) {
                        window.clearTimeout(timeout);
                        output(`✅ Test passed ${testCase}`);
                        resolve();
                    }
                }).catch(reject);
            });
        } catch (e) {
            output(`❌ Failed ${testCase}: exception ${e} ${e.stack}`);
        } finally {
            if (prototype.afterEach) {
                await prototype.afterEach.apply(this.#testClassInstance);
            }
        }
    }

    async runAll()
    {
        const SPECIAL_FUNCTIONS =
            ['beforeEach', 'afterEach', 'beforeAll', 'afterAll', 'constructor'];
        const prototype = Object.getPrototypeOf(this.#testClassInstance);
        const testFunctions =
            Object.getOwnPropertyNames(prototype).filter(
                entry => SPECIAL_FUNCTIONS.indexOf(entry) === -1);

        if (prototype.beforeAll)
            await prototype.beforeAll.apply(this.#testClassInstance);
        for (const fn of testFunctions)
            await this.run(fn);
        if (prototype.afterAll)
            await prototype.afterAll.apply(this.#testClassInstance);
    }
}