LoginSignup
4
7

More than 5 years have passed since last update.

VSCodeの拡張機能開発でユーザー設定を変えながら単体テストする

Posted at

VSCodeの拡張機能開発で単体テストする際に、ユーザーが設定した値に応じた動作をテストする方法をまとめました。

前提条件

下記のpackage.json内で定義されたconfigurationを、取得するSmapleクラスのgetParamメソッドをテストすることを想定して解説します。

package.json
省略
"contributes": {
    "configuration": {
        "type": "object",
        "title": "Sample configuration",
        "properties": {
            "extension.myParam": {
                "type": "string",
                "default": "",
                "description": "sample value"
            }
        }
    }
},
省略
src/Sample.ts
import * as vscode from 'vscode';

export class Sample {
  public getParam(): string {
    let configuration: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('extension');

    if (configuration.myParam.lenth > 0) {
      return configuration.myParam;
    }
    return "None";
  }
}

updateメソッドで任意の値を設定する

vscode.workspace.getConfigurationで現在のconfigurationを取得します。
更にupdateメソッドを実行することで任意の値を設定することが可能です。
第一引数がconfigurationの名称、第二引数が設定する値。

let settings = vscode.workspace.getConfiguration("extension");
setting.update("myParam", "hoge"); // myParamをhogeに変更

テストする

update実行後、そのままテストを書いても設定が反映される前にassertが実行され、テストは失敗します。
updateはThenableを返すので、実行完了を待ってからテストする必要があります。
Mochaには実行完了を待ってからテストする書き方が何通りかありますが、async/awaitを使って書くと下記のようになります。

src/test/extension.test.ts
import * as assert from 'assert';
import * as vscode from 'vscode';
import { Sample} from '../Sample';

suite("Sample Tests", () => {
  test("Test getParam method", async () => {
    let extension = new Sample();
    let settings = vscode.workspace.getConfiguration("extension");

    await setting.update("myParam", "hoge").then(() => {
      assert.equal(extension.getParam(), "hoge");
    });

    await setting.update("myParam", "").then(() => {
      assert.equal(extension.getParam(), "None");
    });
  });
});

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7