Unit test in Node js

117 views Asked by At

I'm learning unit testing in node js using Tape.js, and so far I only find it useful to test the result returned by a function, but what what about to test if a callback has been called exactly n times?

I have this function which calls a callback function n times:

    const repeatCallback = (n, cb) => {
        for (let i = 0; i < n; i++) {
            cb();
        }
    }

module.exports = repeatCallback;

And the tape test:

const repeatCallback = require('./repeatCallback.js');
    const test = require('tape');



    test('repeat callback tests', (t) => {
    t.plan(3);
        repeatCallback(3, () => {console.log('callack called');})
    });

And I'm getting the error : not ok 1 plan != count

How do I update in my test the count to match the number of times that have been called?

THanks

1

There are 1 answers

0
Michał Perłakowski On

Just count how many times the function was called:

const repeatCallback = require('./repeatCallback.js');
const test = require('tape');

test('repeat callback tests', (t) => {
  t.plan(1);
  let count = 0;
  repeatCallback(3, () => { count++; });
  t.equal(count, 3);
});