@happybits/dud

0.0.13 • Public • Published

dud.js

Experimental JavaScript testing library.

With this testing library you can comment your functions with simple test cases. When dud.js is executed it will run your tests from the comments.

The benefits are that you can write short and expressive test cases + your test cases are physically close to your functions. A side effect is that test cases often gives a pretty good description of what your function is supposed to do (so you don't need any normal comments)

I work as a teacher and currently use this in my education, but I think the idea might work in the real world as well :)

Example 1

Here's an example of a function with five tests.

/* 
    [1, 2, 3, 4]         ➞ [2, 4]
    ["A", "B", "C", "D"] ➞ ["B", "D"]
    ["A", "B"]           ➞ ["B"]
    []                   ➞ []
    null                 ➞ null
*/

function pickEverySecondElement(list) {
    if (list === null)
        return null

    let result = []

    for (let i = 1; i < list.length; i = i + 2) {
        result.push(list[i])
    }
    return result;
}

A ten minute clip showing how to use dud.js:

https://youtu.be/2sV_dMO46as

Example 2

Of course you can have multiple parameters. And you can easily create multiple versions of the same function and run the same test cases on all functions.

/*
    5, true     ➞ "*6*"
    20, true    ➞ "*21*"
    10, false   ➞ "11"
    15, false   ➞ "16"
*/

function maybeAddStars(a, b) {
    if (b)
        return `*${a + 1}*`

    return `${a + 1}`
}

function maybeAddStars_oneline(a, b) {
    return b === true ? `*${(a + 1)}*` : (a + 1).toString()
}

Example 3

If you just write normal comments these lines will be ignored. Only lines that contains '➞' will be interpreted as tests. So here we have four tests:

/*
    Get the age of the oldest person.

    [{ "name": "Kalle", "age": 22 }]                                ➞ 22
    [{ "name": "Kalle", "age": 22 }, { "name": "Lisa", "age": 43 }] ➞ 43
    [{ "name": "Kalle", "age": 50 }, { "name": "Lisa", "age": 22 }] ➞ 50

    If no object have the property "age" then zero will be returned.

    [] ➞ 0

*/

function maxage(arr) {
    let result=0
    for(let x of arr)
        result = Math.max(x.age, result)
    return result
}

Getting started in 5 minutes

If you have Visual Studio Code you will get started within 5 minutes.

Just follow the instructions on to this page

Join me

Interested in developing this idea in JavaScript or another language like C#?

Send a mail to oo@happybits.se

Oscar

Package Sidebar

Install

npm i @happybits/dud

Weekly Downloads

1

Version

0.0.13

License

ISC

Unpacked Size

12.3 kB

Total Files

8

Last publish

Collaborators

  • happybits