Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing typescript code with namespaces by jest (ts-jest)

When I try to test a typescript code:

namespace MainNamespace {
    export class MainClass {
        public sum(a: number, b: number) : number {
            return a + b;
        }
    }
}

My test:

describe("main test", () => {
    it("sum test", () => {
        var mainClass = new MainNamespace.MainClass();
        expect(mainClass.sum(3, 2)).toEqual(5);
    })
})

I get the error:

ReferenceError: MainNamespace is not defined

How can I test the code with namespesaces with Jest (ts jest)?

like image 206
Svicer Avatar asked Apr 29 '18 10:04

Svicer


People also ask

Can you test TypeScript with Jest?

Jest is a simple, lightweight testing framework that provides a variety of testing capabilities to JavaScript and TypeScript projects. It provides functionality like assertions, mocking, spies, running tests in parallel, prioritizing failed tests, and coverage analysis.


1 Answers

Here is a working example:

index.ts:

// tslint:disable-next-line: no-namespace
export namespace MainNamespace {
  export class MainClass {
    public sum(a: number, b: number): number {
      return a + b;
    }
  }
}

index.spec.ts:

import { MainNamespace } from './';

describe('MainNamespace', () => {
  it('sum test', () => {
    const mainClass = new MainNamespace.MainClass();
    expect(mainClass.sum(3, 2)).toEqual(5);
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/50085505/index.spec.ts
  MainNamespace
    ✓ sum test (7ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.713s, estimated 10s

Dependencies versions:

"typescript": "^3.6.4",
"jest": "^24.9.0",
"ts-jest": "^24.1.0",

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/50085505

like image 85
slideshowp2 Avatar answered Sep 28 '22 09:09

slideshowp2