12
votes
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");
    });

});
2
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.JB Nizet
I haven't used Karma, but have you tried running tests with karma-typescript? It may take in to account un-accessible code like that. npmjs.com/package/karma-typescriptDeeV

2 Answers

27
votes

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.

3
votes

For future users with a similar question, I've come up with the following system for testing interfaces (which I only use with particularly quirky interfaces, like those I've autogenerated). It's absolutely a workaround, but it does fail my builds if the interface isn't appropriately specified.

First, in the "test", cast an object with the expected fields and types into the interface. For instance,

interface MyInterface = { 
  id: number;
  createTime: Date;
}

test("MyInterface should have appropriate fields and types", () => {
  ({
    id: 3,
    createTime: new Date(),
  } as MyInterface);
})

Then, I added a build step for compiling the TypeScript, which will error if MyInterface is changed.

tsc --noEmit

Again: my tests have no assertions in them, so they're not a real unit test, and this is a workaround. But this process has alerted me to problems a few times, so it serves the purpose.