Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  

Specifications for Calculator using Jasmine and TypeScript

Запись от 8Observer8 размещена 23.02.2019 в 01:08
Показов 1716 Комментарии 0
Метки typescript

Blog content

In this instruction we will study how to write executable specifications for a very simple Calculator project using Jasmine testing framework.

Source code on GitHub: https://github.com/8Observer8/... wserify-ts

If you do not have "browserify" then install it globally using this command:
npm install browserify -g
Note. You can read about why we need "browserify" in this project in my instruction here: Browserify TypeScript

Create the folder "calculator-browserify-ts" and install the necessary package:
npm init -y
npm i -D @types/jasmine
Search in the Internet: jasmine cdn. Create the "SpecRunner.html" file and copy founded CDN links to it:

SpecRunner.html

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Jasmine Spec Runner v3.3.0</title>
    <link rel="shortcut icon" type="image/png"
        href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine_favicon.png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine.min.css">
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/jasmine-html.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.3.0/boot.min.js"></script>
 
    <!-- include source files here... -->
    <script src="dist_client/bundle.js"></script>
 
    <!-- include spec files here... -->
    <script src="dist_specs/bundle.js"></script>
</head>
 
</html>
Let's describe specifications for our calculator. The calculator will have four operations:
  • Add(a, b)
  • Sub(a, b)
  • Mul(a, b)
  • Div(a, b)

If "b == 0" then method "Div" will throw an exception with the text: "Divided by zero".
  • Create the "src_specs" folder. Create the "calculator_tests.ts" in the "src_specs" folder
  • Create the "src_client" folder. Create the "calculator.ts" in the "src_client" folder

Let's create the first specification in the "calculator_tests.ts":

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Calculator } from "../src_client/calculator";
 
describe("Calculator", () =>
{
    it("Add_PositiveNumbers_ReturnsSum", () =>
    {
        // Arrange
        let a = 9;
        let b = 1;
        let expectedSum = 10;
 
        // Act
        let actualSum = Calculator.Add(a, b);
 
        // Assert
        expect(actualSum).toBe(expectedSum);
    });
});
We could try to compile it but we cannot because we do not have the "Calculator" class. Let's add it in the "src_client" folder:

calculator.ts

JavaScript
1
2
3
4
5
6
7
export class Calculator
{
    public static Add(a: number, b: number): number
    {
        return a + b;
    }
}
Add the "tsconfig.specs.json" file in the root of your projects:

"tsconfig.specs.json"

JSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
    "compilerOptions": {
        "sourceMap": true,
        "outDir": "dist_specs"
    },
    "include": [
        "src_specs/calculator_tests.ts",
        "src_client/calculator.ts"
    ],
    "exclude": [
        "node_modules",
        "src_client"
    ]
}
Now we can compile and browserify the specification. Enter two commands:

tsc -p tsconfig.specs.json
browserify dist_specs/src_client/calculator.js dist_specs/src_specs/calculator_tests.js -o dist_specs/bundle.js
You can add these commands to the "package.json" file in the "scripts" section:

JSON
1
2
3
4
5
    "scripts": {
        "build_specs": "tsc -p tsconfig.specs.json",
        "bundle_specs": "browserify dist_specs/src_client/calculator.js dist_specs/src_specs/calculator_tests.js -o dist_specs/bundle.js",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
And you can run these short commands:
npm run build_specs
npm run bundle_specs
Open the "SpecRunner.html" in the browser and you will see that the specification will run.

Try to add another specifications for: Sub, Mul, and Div methods.

Later I will add specification for "Divide by zero" exception.
Изображения
 
Метки typescript
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
Был там один разговор по поводу свободы в материальном мире.
kumehtar 19.08.2026
Суть: рассматривается живое существо, оказавшееся внутри довольно странной системы (этого мира) и пытающееся обустроить в ней свой кусок пространства. Жизнь действительно предъявляет каждому. . .
Когда логика программы не спасает от человеческих ошибок
Maks 18.08.2026
В последнее время всё чаще и чаще сталкиваюсь с таким явлением, как абсолютная невнимательность (или глупость) пользователей. Проявляется это чаще всего на работе в коллективе. Допустим, человек с. . .
Лето уходит
kumehtar 17.08.2026
Мысли в слух
kumehtar 17.08.2026
Забавно, насколько сейчас стала доступна информация. Например о магии, духовном развитии, медитациях, и других подобных направлениях, ранее зачастую тайных, передаваемых от учителя к ученику. Хотя. . .
Перемещение строк из ТЧ в другой документ с учетом текущего пробега
Maks 17.08.2026
Реализация из решения ниже выполнена на примере нетипового документа "Автозапчасти", с ТЧ "Шины". За основу взят алгоритм отсюда: https:/ / www. cyberforum. ru/ blogs/ 359708/ 10838. html Задача: . . .
Саморегулирующийся социальный контракт для сервера cross-section.
Hrethgir 14.08.2026
С кодом конечно таких глубоких размышлений пока не было, впрочем я уже привык к алгоритмизации. Суть предмета записи: снова в диалоге с нейросетью (я взял пока себе ник для учётки админа - Rector). . . .
Часы электронные
Uhbif79 12.08.2026
Выкладываю программу часов. Программа позволяет: 1. Использовать системное время и дату, 2. Есть возможность вводить время и дату вручную. 3. Реализованы 2 будильника: начало и конец рабочего дня. . . .
Часы с будильником на основе класса QLCDNumber
Uhbif79 12.08.2026
Всем добрый день, выкладываю программу часов с будильником на основе класса QLCDNumber. Здесь я пробовал самостоятельно создавал классы, впервые столкнулся с видимостью переменной одного класса из. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru