2

I'm going to test typescript(inversify) code using jest. Below mentioned the code that use to test a controller method.

describe('Test UserController',() =>{

    let userService : UserServiceImpl = new UserServiceImpl();
    let userController : UserController = new UserController(userService);
    let req, res, next;

    beforeEach(() => {
        req = httpMocks.createRequest();
        res = httpMocks.createResponse();
        next = jest.fn();

        req.authorization = 'eyJIjoxNjE0NTc2Mzc3LCJleHAiOjE2NDYxMTIzNzd9';

        jest.mock("../../service/user-service-impl");
    });   
    
    afterEach(() =>{
        jest.resetAllMocks();
    });

    it('getUser method should work properly',async() => {
        const userResponseStub : UserResponse = new UserResponse();
        userResponseStub.username = 'username';
        userResponseStub.email = 'email@test.com';
        
        jest.spyOn(userService, "getUser").mockResolvedValue(userResponseStub);
        const response = await userController.getUser(1);
        expect(response).toBe(userResponseStub);  
    });
});

Below mentioned the configurations related to jest in package.json file

"jest": {
    "verbose": true,
    "testResultsProcessor": "jest-sonar-reporter",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,tsx,ts}",
      "!**/node_modules/**",
      "!**/vendor/**"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "json"
    ],
    "coverageReporters": [
      "lcov",
      "text"
    ],
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/preprocessor.js"
    },
    "testRegex": [
      "(/__tests__/.*|(\\.|/)(test|spec))\\.(ts?|tsx?)$"
    ]
  },
  "jestSonar": {
    "sonar56x": true
  }

Test case is run without any issue. But I'm going to run the application using npm start , getting below error.

describe('Test UserController',() =>{
^
ReferenceError: describe is not defined

Please help me to solve this issue. Any help or workarounds are really appriciated.

Lakshitha Gihan
  • 303
  • 1
  • 19
  • add these spec files to the `exclude` array in your `tsconfig.json` https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#examples – Micael Levi Mar 08 '21 at 16:16
  • @MicaelLevi Thanks for the reply. I added below lines to tsconfig.json file. But the error is same. "include": ["src/**/*"], "exclude": ["node_modules", "**/*.test.ts"] – Lakshitha Gihan Mar 09 '21 at 03:51
  • what if you add `'jest'` to your `tsconfig.json` `types` array? I didn't understand why typescript is type checking these spec files when you run `npm start` – Micael Levi Mar 09 '21 at 04:31
  • @MicaelLevi Below is my tsconfig.json file. { "compilerOptions": { "lib": [ "es6" ], "module": "commonjs", "target": "es6", "experimentalDecorators": true, "emitDecoratorMetadata": true }, "exclude": [ "node_modules", "**/*.test.ts" ] } – Lakshitha Gihan Mar 09 '21 at 08:31
  • add the entry `"types": ["jest", "node"]` to `compilerOptions` and do `npm start`. Show your `start` npm-script – Micael Levi Mar 09 '21 at 18:04
  • @MicaelLevi I add "types": ["jest", "node"] to compilerOptions. But it getting same error. Below I mentioned the scripts object in package.json. "scripts": { "start": "npm run start-env-dev", "start-env-dev": "ts-node src/user-api --NODE_ENV=dev", "start:dev": "ts-node-dev --respawn src/user-api --NODE_ENV=dev", "test": "jest", "test:coverage": "jest --coverage --coverageDirectory=coverage", } – Lakshitha Gihan Mar 10 '21 at 02:29

1 Answers1

0

I've also encoutered "describe is not defined" error while running my app,
and while the issue might be something else - I'll share what was the solution here, because maybe someone else will come to this page searching for answer.

So - in my case the problem was that, in my test file (lets say example.test.tsx)
I've created a mock (lets say const EXAMPLE_MOCK = {name: 'Bob'}),
and I've used this mock in a component (<div>My name is {EXAMPLE_MOCK.name}</div>).

I guess the problem was that, by default, when your application is starting
the code in (...)test(...) files is not built,
but because I've imported something from that file - it had to be built, and compiler found out that there's some unknown function (describe) there.

When you normally run tests you run it with test-specific script, which knows what describe is, so then it's not an issue.

pbialy
  • 1,025
  • 14
  • 26