Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine context + Typescript

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?

like image 646
kubal5003 Avatar asked May 04 '26 03:05

kubal5003


1 Answers

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;
    });
});
like image 151
ComFreek Avatar answered May 05 '26 17:05

ComFreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!