Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create typed variables in beforeAll tests?

There is a common scenario I run into. I need to create a variable in the beforeAll or each.

describe('some test', () => {
  beforeAll(() => {
    const foo = createFoo({}, {});    
  });

  it('returns something', () => {
    // how to access foo?
  });
});

If I do it like that I can't access foo on it tests because it only exists inside beforeAll scope.

To be able to access where I need I have to declare foo inside describe:

describe('', () => {
  let foo;

Or use

this.foo =

The problem with both these approaches is that I lose the type information. And I don't have explicit interfaces for the return type of those kind of functions.

Is there a way to declare foo somewhere where I can access it later and not lose type information?

like image 296
BrunoLM Avatar asked Nov 09 '17 01:11

BrunoLM


1 Answers

You can use the non-null assertion operator (!) to relax the non-null constraint.

describe('some test', () => {
  let foo!: SomeType;
  beforeAll(() => {
    foo = createFoo({}, {});    
  });

  it('returns something', () => {
    expect(foo.bar).toBe(true);
  });
});
like image 140
Oscar Barrett Avatar answered Nov 02 '22 14:11

Oscar Barrett