Why is typescript complaining here that variable is unassigned? Am I missing something obvious with scopes?
test('test', async () => {
let renderResult: RenderResult;
await act(async () => {
renderResult = render(<Component />);
});
await act(async () => {
renderResult.rerender(<Component />);
});
// ERRROR: Variable 'renderResult' is used before being assigned.ts(2454)
expect(renderResult.container.firstElementChild!.getAttribute('src')).toBe('original');
});
The error "Variable is used before being assigned" occurs when we declare a variable without assigning a value to it or only assign a value if a condition is met. To solve the error, change the variable's type to be possibly undefined or give it an initial value.
async / await support in ES6 targets (Node v4+)TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above.
You are getting this error, because you have "strictNullChecks": true
in your tsconfig.json. So the compiler shows you that the variable is possibly has value of undefined.
Options here are
""
for String, []
for Array, etc),expect(renderResult!.container.firstEleme...
),strictNullChecks
in your tsconfig.json,But IMHO if you are using strictNullChecks
, you should consider using null-object pattern.
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