How to unit test model interfaces in typescript?

好久不见. 提交于 2020-05-13 05:24:30

问题


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

});

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/49907035/how-to-unit-test-model-interfaces-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!