Jasmine context + Typescript

你离开我真会死。 提交于 2021-01-28 09:23:44

问题


I'm using Jasmine with Typescript and recently we started using the this context in beforeEach and it.

Example:

beforeEach(() => {
  this.fixture = TestBed.createComponent(blablabla);
});

it('should do something', () => {
   expect(this.fixture).toBeTruthy();
});

The problem is that TypeScript is not smart enough to figure out that this inside beforeEach is exactly the same this as in it. Does anyone know an easy way to 'hint' typescript about this fact?

Is this even possible?


回答1:


You can typehint this in functions. Actually, if you only use arrow functions (in describe, beforeEach and it), the context this will be the outermost global context, I suppose. Since that one cannot be annotated, I suggest passing a regular old-style function to the outermost describe:

// Dummy-type Jasmine functions (only for this MWE)
declare const describe: (msg: string, fun: () => void) => void;
declare const it: (msg: string, fun: () => void) => void;
declare const beforeEach: (fun: () => void) => void;

class A {
    aProperty: string;
}

interface TestSuiteContext {
  myObj: A;
}

describe('Test suite', function (this: TestSuiteContext) {
    beforeEach(() => {
        this.myObj = new A();
    });

    it('should do something', () => {
        const message: string = this.myObj.aProperty;
    });
});


来源:https://stackoverflow.com/questions/49691454/jasmine-context-typescript

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