Reputation: 185
I have some code here. My problem is that I don't manage to understand the way the instance is created. Why we use " : Calculator" ( line 3 ) to use after " new Calculator" (line 4). There is a difference ? I know that I have a problem concerning Typescript but I found this code piece while I was looking for testing in Angular. Also I searched into some tutorials but I don't find explanation.
import { Calculator } from './calculator';
describe('Calculator', () => {
let calculator: Calculator;
beforeEach(() => {
calculator = new Calculator();
});
});
Upvotes: 0
Views: 91
Reputation: 191
The line 3, means the type declaration of your variable, but at first is undefined, so you need to create a new instance of your type, that's why in the next line it does new Calculator()
.
Upvotes: 1
Reputation: 2943
import { Calculator } from './calculator'; // importing Calculator class
describe('Calculator', () => { // Describing feature in BDD manner
let calculator: Calculator;
// Declaring variable calculator so it's accessible within whole describe() block
beforeEach(() => { // This hook will be called before each test in your feature
calculator = new Calculator();
// and therefore will create new instance of a Calculator for each test
});
// Here you probably will see something like
it('should return sum of 2 numbers', () => {
const result = calculator.add(2,3); // actual instance used
expect(result).toEqual(5);
});
});
Upvotes: 1
Reputation: 329
In short, you use the : Calculator to give a type to that variable, on the other hand it is declared outside beforeEach's scope so it can be accesible on the tests.
If you did
beforeEach(() => {
let calculator = new Calculator();
});
calculator won't be accessible.
Upvotes: 1
Reputation: 12960
Your "calculator.ts" file probably has something like:
export class Calculator {
...
}
When you do import { Calculator } from './calculator';
, you import the Calculator class in your current file.
let calculator: Calculator;
will declare a variable calculator
giving it a type Calculator
<- So you specifically say that you will have Calculator
objects in this variable. This is for Typescripts understanding and code completion,
This will create a new instance of the class.
calculator = new Calculator();
Upvotes: 1