In my project we keep files and their tests next to each other.

src
├─ hashing.js
└─ hashing.spec.js

I wanted a quick way to run tests for currently open file regardless which one of the pair is opened. I accomplished this by adding tasks.json to my project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
  "version": "2.0.0",
  "presentation": {
    "echo": true,
    "reveal": "always",
    "focus": false,
    "panel": "shared"
  },
  "tasks": [
    {
      "label": "Run current file tests",
      "type": "shell",
      "isBackground": true,
      "command": "npx",
      "args": [
        "jest",
        "--watch",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "problemMatcher": []
    }
  ]
}

For convenience also configured a keyboard shortcut in keybindings.json:

1
2
3
4
5
6
{
    "key": "cmd+t",
    "command": "workbench.action.tasks.runTask",
    "args": "Run current file tests",
    "when": "editorTextFocus"
},

Now I can run the tests by pressing CMD+T whenever hashing.js or hashing.spec.js is opened.