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?
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With