简体   繁体   中英

Mocking vscode API when unit testing in Jest

Environment:

$ jest -v > 24.9.0
$ node -v > 10.15.3
"@types/vscode": "1.37.0"
"vscode": "^1.37.0"

Inspiration came from Unit test functions that use vscode extension api functions

The layer of indirection has solved part of my problem, However: I need to remove the following function from my extension code so that I can unit test without the dependency of vscode api:

await commands.executeCommand('vscode.open', uri);

The code is refactored to VscodeEnv as follows:

import { Uri, commands, ExtensionContext, WebviewPanel, Disposable } from 'vscode';

export type VSCodeWebviewPanel = WebviewPanel;
export { ExtensionContext as VSCodeExtensionContext };
export { Uri as VSCodeUri };

export class VscodeEnv {
    private static instance: VscodeEnv;
    private constructor() {
        // Nothing added
    }

    public static async executeCommand(command: string, ...rest: any[]): Promise<any | undefined> {
        return commands.executeCommand(command, rest);
    }

    public static registerCommand(command: string, callback: (...args: any[]) => any, thisArg: any): Disposable {
        return commands.registerCommand(command, callback, thisArg);
    }

    public static getInstance(): VscodeEnv {
        if (!VscodeEnv.instance) {
            VscodeEnv.instance = new VscodeEnv();
        }
        return VscodeEnv.instance;
    }
}

Commands are registered as follows:

       const openFileCommand = new OpenFileCmd();
        VscodeEnv.registerCommand(
            ExtensionConfig.Commands.OpenFile.cmd,
            async (uri: VSCodeUri) => openFileCommand.openFile(context, uri.fsPath || ''), this);

And commands are executed as follows:

await VscodeEnv.executeCommand(ExtensionConfig.Commands.Display.cmd, editParams);

The following error message is thrown when I try to call executeCommand with the new flow:

No extension context

Still a few tweaks to incorporate Jest but it allows me to mock vscode API.

Any improvements would be appreciated or any idea why the context is empty?

Thanks.

The issue relates to the params being received by the callback method specified when registering the command:

VSCodeEnv.registerCommand(
            ExtensionConfig.Commands.OpenFile.cmd,
            async (uri: VSCodeUri) => openFileCommand.openFile([context, (uri && uri.fsPath) || '']),
            this
        );

Where the implementation needed to change to the following:

public async openFile(params: any[]): Promise<void> {

In order for object destructing to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM