tape-case v2.2.0
tape-case
tape-case
can help when you need to test the output of a pure function, against different input values.
In this case usually you're forced to write multiple assertions in the same unit test, or to write more than one unit test. In my opinion both these approach are not optimal.
When you run more than one assertion into a unit test, it becomes increasingly harder for another developer (and maybe for you too) to understand what the purpose of the test really is.
Writing a lot of test for the same function, supposing you would only change the input parameters, requires lots of boilerplate code, or abstraction, which are not really needed... instead a good unit test should be as straightforward as it could be.
tape-case
allows to wrap multiple test case against the same system.
usage
Suppose you want to test the following function, sum
; it just s the sum of all its input parameters.
function sum(...args){
return args.reduce((a,b) => a+b, 0)
}
With tape-case
writing different test case is pretty straightforward:
const testcase = require('tape-case')
const sum = require('./sum')
const testcases = [
{ args: [42], expectedResult: 42 },
{ args: [42, 0], expectedResult: 42 },
{ args: [40, 2], expectedResult: 42 },
{ args: [8, 20, 4, 10], expectedResult: 42 }
// ... eventually other test case here
]
testcase(testcases, sum)
// or even
testcase(testcases, function(...args) {
// if you need to do something else before running the function under test
return sum(...args)
});
Now it's even simpler to add another test case, if you even need it.
api
function tapecase(cases, func, context);
cases
: it's the array containing the test cases.Each test case should be an object with
args
,expectedResult
properties.Since version
1.2.0
, it's even possible to omit theexpectedResult
, in case you want to assert the expected value is strict equal totrue
.Before version
2.0.0
theexpectedResult
property was called simplyresult
; the new name should make also more clear that this property is meant to be the expected result of the function under test.func
: it's the function in which you implement the test.It should return the value returned by the function under test.
context
: it's the context on whichfunc
will be executed.It's optional.
install
You can install tape-case
from npm as usual:
npm i tape-case --save-dev