Test spies are function stand-ins that are used to assert if a function's
internal behavior matches expectations. Test spies on methods keep the original
behavior but allow you to test how the method is called and what it returns.
Test stubs are an extension of test spies that also replaces the original
methods behavior.
Spying
Say we have two functions, square and multiply, if we want to assert that
the multiply function is called during execution of the square function we
need a way to spy on the multiply function. There are a few ways to achieve
this with Spies, one is to have the square function take the multiply
multiply as a parameter.
This way, we can call square(multiply, value) in the application code or wrap
a spy function around the multiply function and call
square(multiplySpy, value) in the testing code.
// asserts that multiplySpy was called at least once and details about the first call. assertSpyCall(multiplySpy, 0, { args: [5, 5], returned:25, });
// asserts that multiplySpy was only called once. assertSpyCalls(multiplySpy, 1); });
If you prefer not adding additional parameters for testing purposes only, you
can use spy to wrap a method on an object instead. In the following example, the
exported _internals object has the multiply function we want to call as a
method and the square function calls _internals.multiply instead of
multiply.
This way, we can call square(value) in both the application code and testing
code. Then spy on the multiply method on the _internals object in the
testing code to be able to spy on how the square function calls the multiply
function.
try { assertEquals(square(5), 25); } finally { // unwraps the multiply method on the _internals object multiplySpy.restore(); }
// asserts that multiplySpy was called at least once and details about the first call. assertSpyCall(multiplySpy, 0, { args: [5, 5], returned:25, });
// asserts that multiplySpy was only called once. assertSpyCalls(multiplySpy, 1); });
One difference you may have noticed between these two examples is that in the
second we call the restore method on multiplySpy function. That is needed to
remove the spy wrapper from the _internals object's multiply method. The
restore method is called in a finally block to ensure that it is restored
whether or not the assertion in the try block is successful. The restore
method didn't need to be called in the first example because the multiply
function was not modified in any way like the _internals object was in the
second example.
Method spys are disposable, meaning that you can have them automatically restore
themselves with the using keyword. Using this approach is cleaner because you
do not need to wrap your assertions in a try statement to ensure you restore the
methods before the tests finish.
// asserts that multiplySpy was called at least once and details about the first call. assertSpyCall(multiplySpy, 0, { args: [5, 5], returned:25, });
// asserts that multiplySpy was only called once. assertSpyCalls(multiplySpy, 1); });
Stubbing
Say we have two functions, randomMultiple and randomInt, if we want to
assert that randomInt is called during execution of randomMultiple we need a
way to spy on the randomInt function. That could be done with either of the
spying techniques previously mentioned. To be able to verify that the
randomMultiple function returns the value we expect it to for what randomInt
returns, the easiest way would be to replace the randomInt function's behavior
with more predictable behavior.
You could use the first spying technique to do that but that would require
adding a randomInt parameter to the randomMultiple function.
You could also use the second spying technique to do that, but your assertions
would not be as predictable due to the randomInt function returning random
values.
Say we want to verify it returns correct values for both negative and positive
random integers. We could easily do that with stubbing. The below example is
similar to the second spying technique example but instead of passing the call
through to the original randomInt function, we are going to replace
randomInt with a function that returns pre-defined values.
The mock module includes some helper functions to make creating common stubs
easy. The returnsNext function takes an array of values we want it to return
on consecutive calls.
functionrandomMultiple(value: number): number { returnvalue * _internals.randomInt(-10, 10); }
const_internals = { randomInt };
Deno.test("randomMultiple uses randomInt to generate random multiples between -10 and 10 times the value", () => { constrandomIntStub = stub(_internals, "randomInt", returnsNext([-3, 3]));
try { assertEquals(randomMultiple(5), -15); assertEquals(randomMultiple(5), 15); } finally { // unwraps the randomInt method on the _internals object randomIntStub.restore(); }
// asserts that randomIntStub was called at least once and details about the first call. assertSpyCall(randomIntStub, 0, { args: [-10, 10], returned: -3, }); // asserts that randomIntStub was called at least twice and details about the second call. assertSpyCall(randomIntStub, 1, { args: [-10, 10], returned:3, });
// asserts that randomIntStub was only called twice. assertSpyCalls(randomIntStub, 2); });
Like method spys, stubs are disposable, meaning that you can have them automatically
restore themselves with the using keyword. Using this approach is cleaner because
you do not need to wrap your assertions in a try statement to ensure you restore the
methods before the tests finish.
functionrandomMultiple(value: number): number { returnvalue * _internals.randomInt(-10, 10); }
const_internals = { randomInt };
Deno.test("randomMultiple uses randomInt to generate random multiples between -10 and 10 times the value", () => { usingrandomIntStub = stub(_internals, "randomInt", returnsNext([-3, 3]));
// asserts that randomIntStub was called at least once and details about the first call. assertSpyCall(randomIntStub, 0, { args: [-10, 10], returned: -3, }); // asserts that randomIntStub was called at least twice and details about the second call. assertSpyCall(randomIntStub, 1, { args: [-10, 10], returned:3, });
// asserts that randomIntStub was only called twice. assertSpyCalls(randomIntStub, 2); });
Faking time
Say we have a function that has time based behavior that we would like to test.
With real time, that could cause tests to take much longer than they should. If
you fake time, you could simulate how your function would behave over time
starting from any point in time. Below is an example where we want to test that
the callback is called every second.
With FakeTime we can do that. When the FakeTime instance is created, it
splits from real time. The Date, setTimeout, clearTimeout, setInterval
and clearInterval globals are replaced with versions that use the fake time
until real time is restored. You can control how time ticks forward with the
tick method on the FakeTime instance.
A mocking and spying library.
Test spies are function stand-ins that are used to assert if a function's internal behavior matches expectations. Test spies on methods keep the original behavior but allow you to test how the method is called and what it returns. Test stubs are an extension of test spies that also replaces the original methods behavior.
Spying
Say we have two functions,
squareandmultiply, if we want to assert that themultiplyfunction is called during execution of thesquarefunction we need a way to spy on themultiplyfunction. There are a few ways to achieve this with Spies, one is to have thesquarefunction take themultiplymultiply as a parameter.This way, we can call
square(multiply, value)in the application code or wrap a spy function around themultiplyfunction and callsquare(multiplySpy, value)in the testing code.If you prefer not adding additional parameters for testing purposes only, you can use spy to wrap a method on an object instead. In the following example, the exported
_internalsobject has themultiplyfunction we want to call as a method and thesquarefunction calls_internals.multiplyinstead ofmultiply.This way, we can call
square(value)in both the application code and testing code. Then spy on themultiplymethod on the_internalsobject in the testing code to be able to spy on how thesquarefunction calls themultiplyfunction.One difference you may have noticed between these two examples is that in the second we call the
restoremethod onmultiplySpyfunction. That is needed to remove the spy wrapper from the_internalsobject'smultiplymethod. Therestoremethod is called in a finally block to ensure that it is restored whether or not the assertion in the try block is successful. Therestoremethod didn't need to be called in the first example because themultiplyfunction was not modified in any way like the_internalsobject was in the second example.Method spys are disposable, meaning that you can have them automatically restore themselves with the
usingkeyword. Using this approach is cleaner because you do not need to wrap your assertions in a try statement to ensure you restore the methods before the tests finish.Stubbing
Say we have two functions,
randomMultipleandrandomInt, if we want to assert thatrandomIntis called during execution ofrandomMultiplewe need a way to spy on therandomIntfunction. That could be done with either of the spying techniques previously mentioned. To be able to verify that therandomMultiplefunction returns the value we expect it to for whatrandomIntreturns, the easiest way would be to replace therandomIntfunction's behavior with more predictable behavior.You could use the first spying technique to do that but that would require adding a
randomIntparameter to therandomMultiplefunction.You could also use the second spying technique to do that, but your assertions would not be as predictable due to the
randomIntfunction returning random values.Say we want to verify it returns correct values for both negative and positive random integers. We could easily do that with stubbing. The below example is similar to the second spying technique example but instead of passing the call through to the original
randomIntfunction, we are going to replacerandomIntwith a function that returns pre-defined values.The mock module includes some helper functions to make creating common stubs easy. The
returnsNextfunction takes an array of values we want it to return on consecutive calls.Like method spys, stubs are disposable, meaning that you can have them automatically restore themselves with the
usingkeyword. Using this approach is cleaner because you do not need to wrap your assertions in a try statement to ensure you restore the methods before the tests finish.Faking time
Say we have a function that has time based behavior that we would like to test. With real time, that could cause tests to take much longer than they should. If you fake time, you could simulate how your function would behave over time starting from any point in time. Below is an example where we want to test that the callback is called every second.
With
FakeTimewe can do that. When theFakeTimeinstance is created, it splits from real time. TheDate,setTimeout,clearTimeout,setIntervalandclearIntervalglobals are replaced with versions that use the fake time until real time is restored. You can control how time ticks forward with thetickmethod on theFakeTimeinstance.