UNPKG

jsunittests

Version:

A quick way to make unittests for your code

58 lines (49 loc) 1.77 kB
let rich = require("noderich.js"); class TestResults { constructor(examples) { this.total = 0; this.passed = 0; this.examples = examples; this.answers = []; this.computed = false; this.percent = 0.0; } add_results(expected, result) { if (expected === result) { this.passed++; } this.total++; this.answers.push(result); } compute() { this.percent = Math.round(this.passed / this.total * 100 * 100) / 100; this.computed = true; } print_results(show_succeded = false) { if (!this.computed) { this.compute(); } if (this.percent === 100) { console.log(`${rich.Style.BRIGHT}${rich.Fore.GREEN}All tests passed! (100%)${rich.Style.RESET_ALL}`); return; } for (let i = 0; i < this.examples.length; i++) { let expected = this.examples[i][1]; let result = this.answers[i]; if (result !== expected || show_succeded) { console.log(`Test ${i + 1} [${result === expected ? 'SUCCEEDED' : 'FAILED'}]: ${this.examples[i][0]} -> ${expected} (got ${result})`); } } console.log(`\n${rich.Style.BRIGHT}${rich.Fore.GREEN}Failed ${this.total - this.passed} tests (${this.percent}%)${rich.Style.RESET_ALL}`) } } function run_tests(examples, func) { let results = new TestResults(examples); for (let i = 0; i < examples.length; i++) { let example = examples[i]; let result = func(example[0]); results.add_results(example[1], result); } return results; } export { run_tests, TestResults };