← Back to blog

How to create and use code snippets in VsCode

Some time ago I didn't understand what is code snippet and why I should use them. But when I started writing a lot of unit tests I understood how snippets can simplify my life. In this small article I will show you how to automate writing JS unit tests using snippets.

Let's check this unit test:

describe("MyAwesomeComponent", () => {
  it("should do something", () => {
    // ... some code here
  });

  it("should do something another", () => {
    // ... some code here
  });
});

So every time you need to write manually these describe(..., it(... boilerplate. Quite annoying, right? Snippets helps to avoid this routine and concentrate on writing code.

So let's begin.

To create your own snippet open Command palette (Menu View - Command palette... or using key combination Ctrl + Shift + p) and open there Preferences: Configure user snippets. Now you can select for which filetype (or global) you want to create. I will create for Typescript:

Select snippet file

Now in opened file you should be able to insert your custom snippets. Let's create one for adding it(... code block:

"Add test method": {
  "prefix": "it",
  "body": ["it('$1', () => {", "  $2", "});"],
  "description": "Adds test method"
}

where:

  • Add test method means the description of your snippet
  • prefix is what you will type in editor to execute snippet
  • body is actual body of code. It is array, where each element means line of code:

    • \$1 and \$2 are placeholders where will be cursor placed after selecting snippet. Can jump between using Tab and Shift+Tab key combinations.
  • description is what you will see in popup dialog as ...hm... description

Let's check how it is working:

  • Somewhere in .ts file start typing it and you will see a code complete popup:

    snippet-choose

  • select it and vscode will put generated block of code and set cursor to that place where was first placeholder ($1) defined:

    snippet-extracted

Now you can create your own snippets and increase your productivity.

For more information visit official guide: https://code.visualstudio.com/docs/editor/userdefinedsnippets

snippet live