【问题标题】:Mocking vscode API when unit testing in Jest在 Jest 中进行单元测试时模拟 vscode API
【发布时间】:2019-10-08 16:37:10
【问题描述】:

环境:

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

灵感来自Unit test functions that use vscode extension api functions

间接层解决了我的部分问题!但是,我需要从我的扩展代码中删除以下函数,以便我可以在不依赖 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。

任何改进都将不胜感激,或者知道为什么上下文为空?

谢谢。

【问题讨论】:

  • 所以它似乎与 registerCommand 回调有关:VSCodeEnv.registerCommand( ExtensionConfig.Commands.cmd, async (params: DisplayParams) =&gt; command.display({ ...params, context }), this ); 使用此代码我可以看到正在传递的 params 对象现在已经填充了上下文,但所有其他参数都是空的/未定义的。因此,当调用 executeCommand 时,参数会丢失!

标签: javascript jestjs vscode-extensions


【解决方案1】:

问题与注册命令时指定的回调方法接收的参数有关:

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

实施需要更改为以下内容:

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

为了使对象破坏工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2020-04-06
    • 1970-01-01
    • 2020-07-26
    • 2018-09-04
    • 2013-11-12
    • 2018-11-21
    • 2018-10-19
    相关资源
    最近更新 更多