簡體   English   中英

Mocking vscode API 在 Jest 中進行單元測試時

[英]Mocking vscode API when unit testing in Jest

環境:

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

靈感來自使用 vscode 擴展 api 函數的單元測試函數

間接層解決了我的部分問題,但是:我需要從我的擴展代碼中刪除以下 function 以便我可以在沒有 vscode api 依賴的情況下進行單元測試:

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

代碼重構為VscodeEnv如下:

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;
    }
}

命令注冊如下:

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

命令執行如下:

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

當我嘗試使用新流程調用executeCommand時,會引發以下錯誤消息:

沒有擴展上下文

仍然需要一些調整來合並 Jest,但它允許我模擬 vscode API。

任何改進都會受到贊賞或知道為什么上下文是空的?

謝謝。

該問題與注冊命令時指定的回調方法接收的參數有關:

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

實施需要更改為以下內容:

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

為了使 object 破壞工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM