Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test model interfaces in typescript?

export interface User {
    name: string;
}

How can I unit test the above interface, so Karma could show it in the code coverage report?

I already tried creating the object and assert some properties, but didn't work. The test passes but karma doesn't consider it in the code coverage report.

import { User } from "./user";

describe('User', () => {

    it('test', () => {
        const obj: User = {
            name: "xxx",

        }
        expect(obj.name).toEqual("xxx");
    });

});
like image 556
brazuka Avatar asked Apr 18 '18 18:04

brazuka


People also ask

How do I run a unit test in TypeScript?

For TypeScript, unit tests are run against the generated JavaScript code. In most TypeScript scenarios, you can debug a unit test by setting a breakpoint in TypeScript code, right-clicking a test in Test Explorer, and choosing Debug.

Can we write unit test for interface?

To test an interface with common tests regardless of implementation, you can use an abstract test case, and then create concrete instances of the test case for each implementation of the interface.

Should unit tests be written in TypeScript?

Another argument in favor of writing your unit tests in TypeScript is that unit tests serve as documentation. If you have unit tests code that exercises production code with the same type system, developers are more likely to understand the mechanisms of it all when, for example, attempting a refactor.

Where do unit tests go TypeScript?

We would follow the conventions: Place Source JS/TS files in src folder and tests typescript files in tests folder.


1 Answers

You can't. There is no code to cover here: nothing is executable.

And interfaces only exist at compile-time. They don't exist at runtime.

like image 135
JB Nizet Avatar answered Sep 28 '22 02:09

JB Nizet