はじめに
vscode.window.withProgress()
を呼び出すコマンドをテストしたときに、それは発生した。
TL;DR
await
を忘れずにつけよう。
テキストを挿入しても内容が更新されない問題
前提として、withProgress()
に渡すコールバックの中で、非同期関数を呼び出していた。
そして、その非同期関数を呼び出した後、アクティブなエディタを取得して、選択したテキストの末尾に生成したテキストを挿入していた。
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
...
},
async (progress, token) => {
return new Promise(async (resolve) => {
...
const messages = await Promise.all(...);
await editor?.edit((textEditor: vscode.TextEditorEdit) => {
for (const index in selections) {
const selection = selections[index];
const text = texts[index];
const message = messages[index];
if (selection && text) {
textEditor.insert(selection.end, "\n" + message);
}
}
});
resolve(null);
});
}
);
これを次のようにテストしたところ、openTextDocument()
を呼び出した際に渡したcontent
の値から変化せず、strictEqual()
が失敗に終わった。
const document = await vscode.workspace.openTextDocument({
content: selectedText,
});
...
await vscode.commands.executeCommand("extension.command");
...
assert.strictEqual(
document?.getText(),
`${selectedText}${newCOntent}`
);
await
のつけ忘れ
これは自分の凡ミスなのだが、結局のところawait
のつけ忘れだった。
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
...
},
...
);
await
をつけ忘れた理由
参考にしていたコードでは次のようにwithProgress()
を呼び出していた。
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
...
},
...
);
ただ、僕の場合はこのコードを呼び出し後も処理を行う必要があったため、return
をつけずにそのまま呼び出していた。
デバッグ時にはこの問題に気づかなかったため、テストをしたときに初めて気がついた。
まとめ
vscode.window.withProgress()
を呼び出すときは必ずawait
のつけ忘れを確認しましょう。(return
する場合は除く)
あと、テストはきちんと書きましょう。デバッグだけでは気づかない問題に出会うことができます。