使用vscode扩展api函数的单元测试函数 [英] Unit test functions that use vscode extension api functions

查看:309
本文介绍了使用vscode扩展api函数的单元测试函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种单元测试功能的方法,其中包括vscode扩展api中包含的辅助功能,例如 showQuickPick .用法示例:vscode.window.showQuickPick(['one', 'two']);.

I am trying to figure out a way to unit test functions, which include helper functions included in the vscode extension api, such as showQuickPick. Example usage: vscode.window.showQuickPick(['one', 'two']);.

我一直在尝试对它们进行存根和模拟,但是尽管我不确定这是否是正确的方法,但我还是没有运气.

I have been trying to stub and mock those, but while I am not sure if that's even the right way to go, I haven't had any luck with it anyway.

完整的示例可能类似于:

A complete example could look something like:

logic.js

export async function unitTestMe(): Promise<string> {
  const quickPickAnswer: string = vscode.window.showQuickPick(['one', 'two']);
  return quickPickAnswer;
}

logic.test.js

import { unitTestMe } from './logic';
describe('should return user input', () => {
  test('', () => {
     const expected: string = 'expect me';
     const actual: string = await unitTestMe();
     expect(actual).to.eql(expected);
  })
})

推荐答案

这是我在当前项目中的操作方式:我创建了一个名为VscodeEnvironment的类,在其中包装了Vs Code API(一个间接层)

Here is how I did it in my current project: I created a class called VscodeEnvironment where I wrapped Vs Code API (A layer of indirection)

export class VscodeEnvironment {
    public getActiveTextEditor(): vscode.TextEditor{
        return vscode.window.activeTextEditor;
    }

    public showErrorMessage(message: string): void {
        vscode.window.showErrorMessage(message);
    }

    public showQuickPick<T extends QuickPickItem>(items: T[] | Thenable<T[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<T | undefined> {
        return vscode.window.showQuickPick(items, options, token);
    }
}

在单元测试中,我设置了一个VscodeEnvironment存根以返回已解决的Promise:

In my unit tests, I set up a VscodeEnvironment stub to return a resolved promise:

let vscodeEnvStub = moq.Mock.ofType(VscodeEnvironment);
vscodeEnvStub.setup(x => x.showQuickPick(moq.It.isAny(), moq.It.isAny())).returns(()=>Promise.resolve<QuickPickItem>(fakeItem));

我使用的是typemoq,但在其他模拟框架中应该没有太大的不同

I'm using typemoq, but it should not be very different in other mocking frameworks

这篇关于使用vscode扩展api函数的单元测试函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆