how to run jest test from multiple locations in VSCode

Viewed 463

I managed to mock typeorm to an extent but then now I'm facing a strange issue that I'll illustrate here.

import { myEntity } from './entity';
import typeorm = require('typeorm');

describe('test suire'), () => {

  let myRepository: typeorm.Repository<myEntity>;

  test('my test case', () => {

    typeorm.Repository = jest.fn().mockReturnValue({
      createQueryBuilder: jest.fn().mockReturnValue({
        where: jest.fn().mockReturnThis(),
        getMany: jest.fn().mockReturnValue([]);
      })
    });

    myRepository = new typeorm.Repository();

    expect(myRepository.createQueryBuilder).toHaveBeenCalledTimes(0);

  })
})

I have a package structure like this:

root/
    package.json
    project1/
            package.json
            src/
               the_above_test.spec.ts

When I run node_modules/.bin/jest path_to_above_test.spec.ts from project1 it works. But when I run the same command from root I get:

Matcher error: received value must be a mock or spy function

Received has value: undefined at line:

    expect(myRepository.createQueryBuilder).toHaveBeenCalledTimes(0);

The intention here is to debug the test from within VS Code. But since VS code is open at the root level, it executes the test from there. If there's no bug in my code, how can I tell VS Code to run the test from the project1 directory?

1 Answers

You can specify different jest configurations in your /.vscode/launch.json

Each configuration will have it's own working directory, specified using "cwd".

here's a working example:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "name": "functions",
            "request": "launch",
            "program": "${workspaceFolder}/packages/functions/node_modules/jest/bin/jest",
            "args": [
                "./test/eventHooks.test.ts",
                "--runInBand"
            ],
            "cwd": "${workspaceFolder}/packages/functions",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"

        },
        {
            "type": "node",
            "name": "functions",
            "request": "launch",
            "program": "${workspaceFolder}/packages/types/node_modules/jest/bin/jest",
            "args": [
                "./test/eventHooks.test.ts",
                "--runInBand"
            ],
            "cwd": "${workspaceFolder}/packages/types",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"

        }

    ]
}
Related