问题
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