Skip to content

isocialPractice/exercise-vscode-extension

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Exercise VSCode Extension

Learning exercise turning the Getting Started tutorial on Visual Studio Code into a prompt quiz extension.

Document Navigation:

Quickstart

Use yeoman temporarily.

npx --package yo --package generator-code -- yo code

Use yeoman globally.

npm install --global yo generator-code
yo code .

Note

Use yo code . instead of yo code to create in current directory.

yeoman fields

Update package.json and src/extension.ts.

`package.json`
{
  "name": "exercise-vscode-extension",
  "displayName": "exercise-vscode-extension",
  "description": "Extension that works as a customizable learning exercise.",
  "version": "0.0.1",
  "engines": {
    "vscode": "^1.106.1"
  },
  "categories": [
    "Other"
  ],
  "activationEvents": [],
  "main": "./out/extension.js",
  "contributes": {
    "commands": [
      {
        "command": "exercise-vscode-extension.exercise",
        "title": "exercise"
      }
    ]
  },
  "scripts": {
    "vscode:prepublish": "npm run compile",
    "compile": "tsc -p ./",
    "watch": "tsc -watch -p ./",
    "pretest": "npm run compile && npm run lint",
    "lint": "eslint src",
    "test": "vscode-test"
  },
  "devDependencies": {
    "@types/vscode": "^1.106.1",
    "@types/mocha": "^10.0.10",
    "@types/node": "22.x",
    "typescript-eslint": "^8.46.3",
    "eslint": "^9.39.1",
    "typescript": "^5.9.3",
    "@vscode/test-cli": "^0.0.12",
    "@vscode/test-electron": "^2.5.2"
  }
}
`src/extension.ts`
// extension
// Use a 'Hello world' variation to get started.

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
 const disposable = vscode.commands.registerCommand("exercise-vscode-extension.exercise", () => {
  vscode.window.showInformationMessage("It worked");
 });
 context.subscriptions.push(disposable);
}

export function deactivate() {}

Open src/extension.ts, then press F5 or in command palette (Ctrl+Shift+P) run Debug: Start Debugging. In the debug window run exercise from the command palette (Ctrl+Shift+P). A window with the text "It worked" will appear.

Quickstart Takeaways

Three concepts for a VS Code extension:

  1. Activation Events
    • onCommand in package.json as command.
  2. Contribution Points
    • contributes.commands in package.json makes each command nested in commands available from command palette.
  3. VS Code API
    • commands.registerCommand binds function to registered command in package.json.

package.json

  "contributes": {
    "commands": [
      {
        "command": "exercise-vscode-extension.exercise",
        "title": "exercise"
      }
    ]
  }

src/extension.ts

 vscode.commands.registerCommand("command", () => {});

Extension Anatomy Deep Dive

The Extension Entry File

Every extension exports two functions:

  1. activate(context: vscode.ExtensionContext) - Called when activation event occurs

    • Register commands, providers, and event handlers
    • Subscribe disposables to context.subscriptions
    • One-time initialization code
  2. deactivate() - Called when extension is disabled/uninstalled

    • Cleanup resources
    • Save state if needed
    • Return Promise if async cleanup required

File Structure

.
├── .vscode/
│   ├── launch.json          // Debugging configuration
│   └── tasks.json           // Build tasks
├── src/
│   ├── extension.ts         // Entry point
│   ├── data.json            // Quiz data
│   └── test/
│       └── extension.test.ts
├── out/                     // Compiled JavaScript (generated)
├── package.json             // Extension manifest
├── tsconfig.json            // TypeScript config
└── README.md

Important VS Code APIs Used

API Purpose Example
vscode.commands.registerCommand() Register command registerCommand('exercise', () => {})
vscode.window.showInputBox() Get user text input await showInputBox({ prompt: '...' })
vscode.window.showInformationMessage() Show info notification showInformationMessage('Success!')
vscode.window.showWarningMessage() Show warning notification showWarningMessage('Incorrect')
vscode.window.showErrorMessage() Show error notification showErrorMessage('File not found')

Testing the Extension

Run tests with:

npm test

The extension includes:

  • Unit tests in src/test/extension.test.ts
  • Integration tests with VS Code test runner
  • ESLint for code quality

Testing Exercise Takeaways

The test suite demonstrates essential patterns for VS Code extension testing.

Test Structure

Tests use the Mocha framework with suite() and test() functions:

import * as assert from 'assert';
import * as vscode from 'vscode';

suite('Extension Test Suite', () => {
  vscode.window.showInformationMessage('Test Started');

  test('Test Name', () => {
    assert.strictEqual(x, y);
  });
});

Assertion Methods

assert.strictEqual(actual, expected) - Checks strict equality (===)

assert.strictEqual("a", "a");  // Passes
assert.strictEqual(0, [1, 2, 3].indexOf(1));  // Passes

Parameter order doesn't matter - both work identically:

assert.strictEqual([1, 2, 3].indexOf(1), 0);
assert.strictEqual(0, [1, 2, 3].indexOf(1));

assert.ok(condition, message) - Validates boolean condition

assert.ok(2 > 1, "This should not output.");  // Passes silently
assert.ok(!(2 < 1), "This would output on failure.");  // Passes

Use !() to negate conditions when testing for false cases.

Mock User Input

The quiz simulation test mocks showInputBox() to automate user interaction:

const originalShowInputBox = vscode.window.showInputBox;
const inputs = ['yes', 'answer1', 'answer2', 'exit'];
let inputIndex = 0;

vscode.window.showInputBox = async (options?: vscode.InputBoxOptions): Promise<string | undefined> => {
  if (inputIndex >= inputs.length) {
    return undefined;
  }
  const response = inputs[inputIndex++];
  await new Promise(resolve => setTimeout(resolve, 10));
  return response;
};

try {
  await vscode.commands.executeCommand('exercise-vscode-extension.exercise');
  // Verify behavior
} finally {
  vscode.window.showInputBox = originalShowInputBox; // Restore
}

Key Points:

  • Store original function reference
  • Replace with mock implementation
  • Return predefined sequence of inputs
  • Always restore original in finally block

Promise-Based Test Coordination

For tests that need to wait for async completion without hardcoded timeouts:

  • Use await at end of test.
    • This pattern eliminates race conditions and hardcoded timeouts.
  • Use a helper function, and call at end of test.

Note

Using both will also work.

Using await:

// Before suite - declare tracker
let testCompletionResolve: (() => void) | null = null;
const testCompletionPromise = new Promise<void>((resolve) => {
  testCompletionResolve = resolve;
});

// In last test's finally block - signal completion
if (testCompletionResolve) {
  testCompletionResolve();
}

// In async IIFE - wait for completion
(async () => {
  await testCompletionPromise;
  console.log("All tests complete!");
})();

Using Helper Function:

			// Signal that all tests are complete
			if (testCompletionResolve) {
				testCompletionResolve();
    helperFunction();
			}

Advanced Test: 90% Accuracy Simulation

The quiz simulation test demonstrates:

  • Loading external JSON data
  • Randomly selecting incorrect answers
  • Tracking test metrics
  • Extended timeouts for long-running tests
 test('Quiz simulation with 90% correct answers', async function() {
   this.timeout(30000); // 30 seconds for full quiz

   const totalQuestions = quizData.quiz.length;
   const targetCorrect = Math.floor(totalQuestions * 0.9);
   const incorrectCount = totalQuestions - targetCorrect;

   // Randomly select which questions to answer incorrectly
   const incorrectIndices = new Set<number>();
   while (incorrectIndices.size < incorrectCount) {
     incorrectIndices.add(Math.floor(Math.random() * totalQuestions));
   }

   // Build input sequence with correct/incorrect answers
   quizData.quiz.forEach((question, index) => {
     if (incorrectIndices.has(index)) {
       inputSequence.push('wrong answer');
     } else {
       inputSequence.push(question.answer);
     }
   });
 });

Generating Test Outputs

Use console output for debugging details visible in the terminal:

console.log(`Quiz Results:`);
console.log(`  Total Questions: ${totalQuestions}`);
console.log(`  Expected Correct: ${expectedCorrect}`);

Use vscode.window.showInformationMessage() for messages visible in the test UI.

For this exercise a helper function was created for dual outputs:

dualLog() Helper Function:

function dualLog(msg: string): void {
  if (msg !== "") {
    vscode.window.showInformationMessage(msg);
  }
  console.log(`   ${msg}`);
}

Running Tests

Execute tests from command palette or terminal:

npm test

Or press F5 with test file open to debug tests interactively.

Learning Exercise

This extension evolves from a simple "Hello World" to an interactive quiz system that teaches VS Code extension development concepts.

Phase 1: User Input with showInputBox()

The extension uses vscode.window.showInputBox() to create an interactive quiz experience:

const userAnswer = await vscode.window.showInputBox({
  prompt: `Question ${currentQuestionIndex + 1} of ${totalQuestions}`,
  placeHolder: currentQuestion.question,
  ignoreFocusOut: true,
  validateInput: (text) => {
    if (!text || text.trim() === '') {
      return 'Please enter an answer or type "exit" to quit, "hint" for a hint';
    }
    return null;
  }
});

Key Learning Points:

  • showInputBox() returns a Promise<string | undefined>
  • validateInput provides real-time validation
  • ignoreFocusOut keeps the input box open when clicking elsewhere
  • Returns undefined when user cancels (Escape key)

Phase 2: File System Operations

The extension reads quiz data from data.json:

import * as fs from 'fs';
import * as path from 'path';

const dataPath = path.join(__dirname, '..', 'src', 'data.json');
const quizData: QuizData = JSON.parse(fs.readFileSync(dataPath, 'utf8'));

Key Learning Points:

  • __dirname points to the compiled out/ folder
  • Navigate to source files using path.join()
  • TypeScript interfaces define data structures
  • Node.js fs module for file operations

Phase 3: Interactive Quiz Logic

The quiz implements recursive async functions and user feedback:

const askQuestion = async () => {
  if (currentQuestionIndex >= totalQuestions) {
    // Quiz completed
    return;
  }

  const userAnswer = await vscode.window.showInputBox({ /* ... */ });

  // Handle special commands
  if (userAnswer === 'exit') return;
  if (userAnswer === 'hint') {
    // Show hint and re-ask
    await askQuestion();
    return;
  }

  // Check answer and continue
  currentQuestionIndex++;
  setTimeout(() => askQuestion(), 500);
};

Key Learning Points:

  • Recursive async/await patterns
  • Command handling (exit, hint)
  • Progressive disclosure of information
  • User feedback with showInformationMessage() and showWarningMessage()

Phase 4: Data Structure

Quiz questions are stored in src/data.json:

{
  "quiz": [
    {
      "id": 1,
      "question": "What are the two main functions exported by an extension entry file?",
      "answer": "activate and deactivate",
      "hints": ["One is called when the extension is activated", "One is called when the extension is deactivated"],
      "category": "Extension Anatomy"
    }
  ]
}

Key Learning Points:

  • JSON as configuration/data storage
  • TypeScript interfaces for type safety
  • Separation of code and data
  • Extensible quiz system

Learning Resources

Official Documentation

Sample Extensions

Explore the vscode-extension-samples repository for examples:

Publishing

To publish your extension to the VS Code Marketplace:

  1. Install vsce (Visual Studio Code Extensions):

    npm install -g @vscode/vsce
  2. Package your extension:

    vsce package
  3. Publish (requires publisher account):

    vsce publish

Learn more: Publishing Extensions

Final Notes

Enhanced the current learning exercise extension, making it viably publishable. The final results are at prompt-quiz.

License

See LICENSE file for details.

About

Learning exercise for VS Code extensions.

Topics

Resources

License

Stars

Watchers

Forks

Languages