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

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

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

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)