Monday, 14 October 2019

Testing pure function on union type which delegates to other pure functions

Suppose you have function which takes a union type and then narrows the type and delegate to one of two other pure functions.

function foo(arg: string|number) {
    if (typeof arg === 'string') {
        return fnForString(arg)
    } else {
        return fnForNumber(arg)
    }
}

Assume that fnForString() and fnForNumber() are also pure functions, and they have already themselves been tested.

How should one go about testing foo()?

  • Should you treat the fact that it delegates to fnForString() and fnForNumber() as an implementation detail, and essentially duplicate the tests for each of them when writing the tests for foo()? Is this repetition acceptable?
  • Should you write tests which "know" that foo() delegate to fnForString() and fnForNumber() e.g. by mocking them out and checking that it delegates to them?


from Testing pure function on union type which delegates to other pure functions

No comments:

Post a Comment