Skip to main content

Unit Test node

Для тестування використовується

Підключено в проектах

  • node
  • nsdi
  • itree
  • geodata

Додавання тестів до проєкту

Для того, щоб додати тести до конкретного проєкту потрібно в корінь проєкту додати папку test з наступною структурою:

- test/
- api/ # конкретна папка з файлами тестів
- data.tets.js # файл з тестами
...
...
- index.test.js # файл, в якому підключаються всі файли тестів та інші залежності
# включаючи функції jest, які наявні в проєкті node
- test.json # файл-конфіг проєкту з параметрами підключення до бд

Function

const { describe, it } = require('node:test');
const assert = require('assert/strict');
const db = require('../test.json');
const funcsWrap = require('../../service/funcs');

const funcs = funcsWrap({ db });
// Creates a box with an equal height and width
describe('funcs', async () => {
it('setTokenById', async () => {
const data = await funcs.setTokenById({ ids: ['122'], mode: 'w', uid: 1 });
console.log(data);
assert.ok(data);
});
});

API

const { describe, it } = require('node:test');
const assert = require('assert/strict');
const app = require('../../../service/fastifyApp');

// Приклад тесту апі методу GET
describe('module/gis/editor', async () => {


it('/api-user/table-list', async () => {

// Виклик API за допомогою app.inject
const res = await app.inject({
method: 'GET',
url: '/api-user/table-list',
});

// Перевірка статус-коду відповіді
assert.equal(res.statusCode, 200);
});
});

// Приклад тесту апі методу POST
it('table is not defined', async () => {
const res = await app.inject({
method: 'POST',
url: '/api-user/insert-data',
// параметри body
body: {
address: '2473936094060611486',
green_space_id: '3216275074147419576',
text: '11',
type: 1,
},
});
assert.equal(res.statusCode, 400);
});

Helper

Тестування через handlebars або через виклик функції


const assert = require('assert/strict');
const { describe, it } = require('node:test');
const { hbSync } = require('../../service/config/initHB');
const ifCond = require('../../module/core/handlebars/helper/ifCond');

describe('num_format', async () => {
const num = 345.55677;
it('ok', async () => {
const data = await hbSync.compile(`{{num_format ${num}}}`)({});
assert.equal(data, '345,56');
});
});

describe('ifCond', async () => {
it('==', () => {
assert.equal(ifCond({ options, __obj, args: ['1', '==', '1'] }), '1');
});

it('!=', () => {
assert.equal(ifCond({ options, __obj, args: ['1', '!=', '1'] }), '2');
});

it('>', async () => {
assert.equal(ifCond({ options, __obj, args: ['1', '>', '2'] }), '2');
});
});

test/index.test.js

Приклад index file - для запуску test. Підключає інші test file

Details
const {
describe, it, before, after, test,
} = require('node:test');
const assert = require('node:assert/strict');

const { clearAll: clearRedis } = require('../../node/service/redis/cache');
const { clearAll: clearPG } = require('../../node/service/pg/cache');
const { dbConfigs } = require('../../node/service/configs');


const db = require('./data.json');
dbConfigs[db.db] = db;

const app = require('../../node/service/fastifyApp');
describe('core test', () => {
test('skip() method with message', (t) => {
t.skip('this is skipped');
});

// before
before(async () => {

});

// test api
require('./api/api.test');

describe('simple', () => {
it('is empty', () => {
assert.equal(0, 0);
});

it('is not empty after push', () => {
assert.equal(1, 1);
});
});

// close db,redis
after(async () => {
await app.close();
// app.close();
clearRedis();
clearPG();
});
});

Run Test

Для того, щоб запустити тести, потрібно з директорії проєкту запустити наступну команду:

node --test .\test\index.test.js

Result

Приклад результату тестування без виявлення помилок:

Details
PS C:\softpro\itree> node --test .\test\index.test.js
hotreload: C:\softpro\node\module local: true
hotreload: C:\softpro\node\service local: true
hotreload: C:\softpro\node\config local: true
▶ core test
skip() method with message (0.15ms) # this is skipped
geo_green_poltava migration start
geo_green_poltava init db start
init project: core undefined site: 13 58
init project: core undefined site: 13 57
init project: itree undefined site: 17 16
i18n reload
geo_green_poltava init db time: 112
hotreload: C:\softpro\itree local: true
i18n reload
project loaded: itree
▶ api
▶ insert data
✔ insert ok (242.8881ms)
✔ table is not defined (1.77ms)
▶ get-green-data
✔ get-green-data ok (5.0776ms)
✔ key is not defined (1.2488ms)
✔ table is not defined (1.2801ms)
▶ get-green-data (7.8701ms)

event_report (get)
✔ event report ok (42.9059ms)
event_report (get) (43.3041ms)

▶ insert data (296.2181ms)

api (296.3351ms)

▶ simple
✔ is empty (0.0566ms)
✔ is not empty after push (0.2192ms)
simple (0.4579ms)

▶ core test (299.174ms)

Приклад результату тестування при виявлені помилки:

Details
PS C:\softpro\itree> node --test .\test\index.test.js
...
▶ api
▶ insert data
✖ insert ok (262.7014ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

200 !== 400

at TestContext.<anonymous> (C:\softpro\itree\test\api\api.test.js:20:14)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Test.run (node:internal/test_runner/test:632:9)
at async Promise.all (index 0)
at async Suite.run (node:internal/test_runner/test:948:7)
at async Promise.all (index 0)
at async Suite.run (node:internal/test_runner/test:948:7)
at async Suite.processPendingSubtests (node:internal/test_runner/test:374:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 400,
operator: 'strictEqual'
}

...

Приклад pipeline для запуску тестів

stages:
- test

img-test:
stage: test
tags:
- local-service-server
variables:
GIT_STRATEGY: none
script:
- cd /data/node && git pull origin dev
- cd /data/project_folder_name && node --test ./test/index.test.js
only:
- dev

Корисні посилання