MZ Unit Testing Plugins

Reposting this from the general questions thread, because maybe it should be it's own thread.
I would be interested in setups or experiences of using unit testing for plugin development.

I have managed to get a simple setup going using the jasmine standalone framework, but would like to go further and integrate it properly into my development workflow by running them automatically by a continuous integration runner whenever I make a pull request in git.

I was wondering if somebody might even already have such a setup running that he could share.

Added the RMMZ prefix because that's what I'm working with but I suppose the question might as well apply to RMMV.
I think @DoubleX might
I did some work on that here: https://github.com/comuns-rpgmaker/typescript-plugin-archetype

It uses jasmine, and there is a github action set up for running the tests on push. It also comes with typescript support and a nice way of writing plugin metadata (built with a tool I wrote too, here: https://github.com/comuns-rpgmaker/plugin-metadata)

There's this project that uses that template and has some actual tests (not many, because I'm lazy, but it serves as an example haha) if you want to see how it works in practice: https://github.com/comuns-rpgmaker/schach-parsing

This works well for simple unit tests. Recently I did some integration-like testing that involved stuff related to PIXI too, but that didn't really go very well, sadly 🙁
I did some work on that here: https://github.com/comuns-rpgmaker/typescript-plugin-archetype

It uses jasmine, and there is a github action set up for running the tests on push. It also comes with typescript support and a nice way of writing plugin metadata (built with a tool I wrote too, here: https://github.com/comuns-rpgmaker/plugin-metadata)

There's this project that uses that template and has some actual tests (not many, because I'm lazy, but it serves as an example haha) if you want to see how it works in practice: https://github.com/comuns-rpgmaker/schach-parsing

This works well for simple unit tests. Recently I did some integration-like testing that involved stuff related to PIXI too, but that didn't really go very well, sadly 🙁
Hmm... That sounds interesting. But I feel like switching to typescript makes the setup more complicated than I thought. Which adds more barriers for contributors.
I just feel that continuous integration might be a bit overkill when it comes to RMMZ plugins, unless you're talking about very complex and colossal ones and/or those written by many plugin developers instead of one.
Also, when it comes to most RMMZ plugins, maybe using GitHub is already enough to cover most of the needs behind continuous integration, and you can make the plugin unit test suite run upon starting the game, so the risks of some plugin implementation changes breaking something unnoticed should be already mitigated 🙂

But seriously, I think the real problem is the difficulty of writing useful unit test suites in RMMZ, and the nature of the RMMZ codebase makes unit testing inherently hard, because most of the functions/methods are far from pure, and many objects are very large(with tons of methods and states), meaning that you'll frequently have to setup quite some test fixtures(that are troublesome to clean up), probably involving many dependencies, sometimes being global/god objects, that are hard to mock, so trying to write useful unit test suite can be really a world of hurt.
On the architectural design level, it's tricky to clearly define the APIs, boundaries and interactions of the modules in the RMMZ codebase, and these things are necessary(but not sufficient) to make a codebase unit-test friendly, so lacking these things makes it usually hard to isolate the parts to be unit-tested in RMMZ.

On the UI layer, RMMZ seems to lack the layer of converting UI rendering commands into actual UI rendering(I actually think that it doesn't even have the concept of UI rendering commands to begin with), and this missed part makes unit testing UI rendering rather difficult:
1. With UI rendering commands, you can setup a test fixture(the current game state set involved), and then with some raw user keyboard/mouse/touch events as inputs, some corresponding UI rendering commands should be the outputs, then you can just write some unit tests to verify whether the actual rendering command sequences are expected, and clean up the test fixture after running those tests
2. If the correct UI rendering commands are produced but the actual UI rendering is still problematic, then it means those UI rendering commands have bugs, and knowing this already simplifies the debugging processes largely
3. Without UI rendering commands, it'd be even hard to fully automate UI tests without manually checking the actually rendered screen by our own eyes, because trying to automate even these things either involves so much UI verification work that almost no ones will really do it, or you'll have to use some kind of AI that can verify the UI itself

Therefore, I think the biggest issue isn't the setup of automated testing frameworks(although it's indeed an issue), but how to write plugins with highly testable codes when the default RMMZ codebase is so hostile on testability, which is still somehow feasible to some extents.
For instance, unit testing whether the plugins properly read their own notetags from the database by mocking the database objects to be tested should be doable, as I've done this in one of my RMMV plugin, although it's still exhausting to me.

Alternatively, you can try to use assertions instead of unit tests, and it seems to me that adding assertions in RMMZ plugins is a much easier, simpler and smaller task than writing unit tests for them(those assertions have saved me dozens of times when I develop an advanced complex RMMV plugin).
Of course, writing loads of assertions for plugins is still tiring, but at least it can help me a lot in debugging(so I've very few unit tests in my plugins but quite some assertions there) 😀
But seriously, I think the real problem is the difficulty of writing useful unit test suites in RMMZ, and the nature of the RMMZ codebase makes unit testing inherently hard, because most of the functions/methods are far from pure, and many objects are very large(with tons of methods and states), meaning that you'll frequently have to setup quite some test fixtures(that are troublesome to clean up), probably involving many dependencies, sometimes being global/god objects, that are hard to mock, so trying to write useful unit test suite can be really a world of hurt.
I feel like I actually do have quite some meaningful unit tests. Correctly updating self switches on the correct map, properly loading/saving data for my quest plugin, etc. I mean sure, not the craziest test cases but imo that's pretty fitting for unit tests.

Here's a quick screenshot of my setup:

Screenshot 2021-06-03 19.37.03.png


Though, since the Jasmine stand-alone starts an actual browser window, things become a lot easier. I haven't managed to get it running on a CI.

I do agree that integration tests are kind of meaningless. I wrote a simple bot plugin like Selenium that fires a sequence of buttons and then performs some assertions but I haven't been actively using that at all...
Assuming that you use GitHub for the CI, maybe it's not truly different from standard CI:
https://docs.github.com/en/actions/guides/about-continuous-integration
https://docs.github.com/en/actions/guides/setting-up-continuous-integration-using-workflow-templates
https://lab.github.com/githubtraining/github-actions:-continuous-integration
In your case, you may have to setup a server that hosts RMMZ files and can run RMMZ(your unit test suite can be run after loading all plugins and setting up environments like game variables and switches, and the game can terminate automatically after running those tests), then when you make a pull request, a GitHub action can be triggered to start RMMZ in that server(or at least try to run an actual browser).
While I haven't tried things like these personally(and I feel that it'd be overkill for RMMZ plugins), it seems to me that maybe the key is to find a way to make the server run RMMZ when you want the CI to test your commits, as I feel that running unit tests without running RMMZ(but not to the point of starting the game though) actually makes things even harder 🙂
Assuming that you use GitHub for the CI, maybe it's not truly different from standard CI:
https://docs.github.com/en/actions/guides/about-continuous-integration
https://docs.github.com/en/actions/guides/setting-up-continuous-integration-using-workflow-templates
https://lab.github.com/githubtraining/github-actions:-continuous-integration
In your case, you may have to setup a server that hosts RMMZ files and can run RMMZ(your unit test suite can be run after loading all plugins and setting up environments like game variables and switches, and the game can terminate automatically after running those tests), then when you make a pull request, a GitHub action can be triggered to start RMMZ in that server(or at least try to run an actual browser).
While I haven't tried things like these personally(and I feel that it'd be overkill for RMMZ plugins), it seems to me that maybe the key is to find a way to make the server run RMMZ when you want the CI to test your commits, as I feel that running unit tests without running RMMZ(but not to the point of starting the game though) actually makes things even harder 🙂

I use GitLab CI but I think that's of little import. Getting the RMMZ files is no problem since the project gets checked out. I currently have it setup for automatic deployment to itch when I make a release tag.
Would like to extend it with a unit test case execution before really firing off the deploys to make sure everything's ok.

Here's my current yml (Warning repo also contains NSFW content):


I tried a generic npm test with jasmine installed but since RMMZ base isn't split up into UI/Non-UI code I ran into the problem that it exploded on the UI stuff like pixi being called when you setup a game...
Then maybe you'll have to have 2 RMMZ versions in your project - 1 for real and 1 just for unit test.
The main idea is that the unit test version should avoid running as many UI codes as possible(to try to solve your problem of exploding on the UI stuff), and there are some files that you may have to change, for instance:

main.js -
JavaScript:
const scriptUrls = [
    // Try to remove these from being loaded in the unit test version
    // "js/libs/pixi.js",
    // "js/libs/pako.min.js",
    // "js/libs/localforage.min.js",
    // "js/libs/effekseer.min.js",
    // "js/libs/vorbisdecoder.js",
    //
    "js/rmmz_core.js",
    "js/rmmz_managers.js",
    "js/rmmz_objects.js",
    "js/rmmz_scenes.js",
    "js/rmmz_sprites.js",
    "js/rmmz_windows.js",
    "js/plugins.js"
];
// Try to remove this from being loaded in the unit test version
// const effekseerWasmUrl = "js/libs/effekseer.wasm";
//

class Main {
    constructor() {
        this.xhrSucceeded = false;
        this.loadCount = 0;
        this.error = null;
    }

    run() {
        this.showLoadingSpinner();
        this.testXhr();
        this.loadMainScripts();
    }

    showLoadingSpinner() {
        // Try to remove these UI codes in the unit test version
        // const loadingSpinner = document.createElement("div");
        // const loadingSpinnerImage = document.createElement("div");
        // loadingSpinner.id = "loadingSpinner";
        // loadingSpinnerImage.id = "loadingSpinnerImage";
        // loadingSpinner.appendChild(loadingSpinnerImage);
        // document.body.appendChild(loadingSpinner);
        //
    }

    eraseLoadingSpinner() {
        // Try to remove these UI codes in the unit test version
        // const loadingSpinner = document.getElementById("loadingSpinner");
        // if (loadingSpinner) {
        //     document.body.removeChild(loadingSpinner);
        // }
        //
    }

    testXhr() {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", document.currentScript.src);
        xhr.onload = () => (this.xhrSucceeded = true);
        xhr.send();
    }

    loadMainScripts() {
        for (const url of scriptUrls) {
            const script = document.createElement("script");
            script.type = "text/javascript";
            script.src = url;
            script.async = false;
            script.defer = true;
            script.onload = this.onScriptLoad.bind(this);
            script.onerror = this.onScriptError.bind(this);
            script._url = url;
            document.body.appendChild(script);
        }
        this.numScripts = scriptUrls.length;
        window.addEventListener("load", this.onWindowLoad.bind(this));
        window.addEventListener("error", this.onWindowError.bind(this));
    }

    onScriptLoad() {
        if (++this.loadCount === this.numScripts) {
            PluginManager.setup($plugins);
        }
    }

    onScriptError(e) {
        this.printError("Failed to load", e.target._url);
    }

    printError(name, message) {
        this.eraseLoadingSpinner();
        if (!document.getElementById("errorPrinter")) {
            const errorPrinter = document.createElement("div");
            errorPrinter.id = "errorPrinter";
            errorPrinter.innerHTML = this.makeErrorHtml(name, message);
            document.body.appendChild(errorPrinter);
        }
    }

    makeErrorHtml(name, message) {
        const nameDiv = document.createElement("div");
        const messageDiv = document.createElement("div");
        nameDiv.id = "errorName";
        messageDiv.id = "errorMessage";
        nameDiv.innerHTML = name;
        messageDiv.innerHTML = message;
        return nameDiv.outerHTML + messageDiv.outerHTML;
    }

    onWindowLoad() {
        if (!this.xhrSucceeded) {
            const message = "Your browser does not allow to read local files.";
            this.printError("Error", message);
        } else if (this.isPathRandomized()) {
            const message = "Please move the Game.app to a different folder.";
            this.printError("Error", message);
        } else if (this.error) {
            this.printError(this.error.name, this.error.message);
        } else {
            this.initEffekseerRuntime();
        }
    }

    onWindowError(event) {
        if (!this.error) {
            this.error = event.error;
        }
    }

    isPathRandomized() {
        // [Note] We cannot save the game properly when Gatekeeper Path
        //   Randomization is in effect.
        return (
            Utils.isNwjs() &&
            process.mainModule.filename.startsWith("/private/var")
        );
    }

    initEffekseerRuntime() {
        this.onEffekseerLoad(); // Just jump to starting the game in the unit test version
        // Try to stop effekseer from being loaded in the unit test version
        // const onLoad = this.onEffekseerLoad.bind(this);
        // const onError = this.onEffekseerError.bind(this);
        // effekseer.initRuntime(effekseerWasmUrl, onLoad, onError);
        //
    }

    onEffekseerLoad() {
        this.eraseLoadingSpinner();
        SceneManager.run(Scene_Boot);
    }

    onEffekseerError() {
        // Try to stop effekseer from being loaded in the unit test version
        // this.printError("Failed to load", effekseerWasmUrl);
        //
    }
}

const main = new Main();
main.run();

rmmz_scenes.js -
JavaScript:
Scene_Boot.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SoundManager.preloadImportantSounds();
    if (DataManager.isBattleTest()) {
        DataManager.setupBattleTest();
        // Stops the game from actually starting in the unit test version
        // SceneManager.goto(Scene_Battle);
        //
    } else if (DataManager.isEventTest()) {
        DataManager.setupEventTest();
        // Stops the game from actually starting in the unit test version
        // SceneManager.goto(Scene_Map);
        //
    } else {
        // Stops the game from actually starting in the unit test version
        // this.startNormalGame();
        //
    }
    this.resizeScreen();
    this.updateDocumentTitle();
};

Then you'll also have to ensure the unit test suites are completely run at the point of Scene_Boot.prototype.start or before that, and maybe you can also call SceneManager.terminate() after running the unit test suites, like calling it at the end of Scene_Boot.prototype.start.
There will be even more places to edit, but I hope you get my idea 🙂

Of course, this approach can lead to at least 2 problems:
1. Whenever the default RMMZ codebase changes, now you'll have to possibly change 2 versions(the real and the unit test ones) instead of just 1 in your project
2. Stripping off UI codes in the unit test version needs to be very careful, otherwise even if the unit test could be run properly, it might still end up missing some real things and giving you some false positives

Original thread: https://forums.rpgmakerweb.com/threads/unit-testing-plugins.137094/