Outline
Another of the tools that comes with Deno is a test runner for both your JavaScript and TypeScript code. All you need to do is use Deno.test
, passing it a name of the test and a function to run. You can import assertions from the asserts file in the testing module. Here's an example of a test for the add
function I created in the previous example, contained in the file add.test.ts
:
// add.test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts';
import { add } from './add.ts';
Deno.test('adding 2 and 2 = 4', () => {
const result = add(2, 2);
assertEquals(result, 4);
})
There is a second way to define a test, where you pass in an object to the test
method. You need to provide at least the name
attribute and fn
attribute's values for it to work:
// math.test.ts
import { assertEquals } from 'https://deno.land/std@0.81.0/testing/asserts.ts';
import { add } from './add.ts';
Deno.test({
name: 'adding 2 and 2 = 4',
fn: () => {
const result = add(2, 2);
assertEquals(result, 4);
}
})
The test is run using the test
command from Deno:
$ deno test
running 1 tests
test adding 2 and 2 = 4 ... ok (2ms)
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
You may notice that I didn't specify any file to run with the deno test
command. That's because by default, the command looks for all *.test.*
files (.test.js and .test.ts files) in your project and runs the tests inside them. You can provide the path to a specific folder or file if you only want certain things tested, however.
There are more options when running tests, so check out the documentation to see all the options available.
Here's the contents of the subtract.ts
file, for which you should write the tests for this assignment.
export function subtract(num1: number, num2: number) {
return num1 - num2;
}