Skip to main content

6.) Testing your code

tip

🥳🎉🎊 Congratulations! You have utilized your Typescript knowledge to implement the Mat2 class! Wait, but how can we be sure that our code is working correctly? Here come unit tests!

How to write unit tests?​

Background: The jest testing framework​

We are using Jest as our test framework.

Jest provides some nice functions to

  1. group tests together (e.g. describe())
  2. declare a unit test (e.g. test())
  3. make assertions (e.g. expect().toBe(), expect().toEqual())

Jest allow us to easily

  1. name our unit tests
  2. group and run them together
  3. see how many tests we have successed and failed
  4. for failing tests, see what are the expected and actual values

Jest has many other utilities, but these are all you need to know for now.

Test examples​

We have provided you with 2 example files for you to explore:

  1. Assignment0_CS4620/src/Tests/Scratch.test.js
  2. Assignment0_CS4620/src/Tests/Mat2.test.js

You should first checkout the Scratch.test.js file, which includes basic example of a Jest test file. The Mat2.test.js file includes tests that will be used to test the correctness of your Mat2 class.

Jest test file explanation​

Example Jest test section
Assignment0_CS4620/src/Tests/Mat2.test.js
describe("Scale Matrix", () => {
test("Scale by 3", () => {
let v = new Vec2(2, 3);
let s = Mat2.Scale(3);
expect(s.times(v)).VecEqual(new Vec2(6, 9));
});
test("Scale by -2", () => {
let v = new Vec2(2, 3);
let s = Mat2.Scale(-2);
expect(s.times(v)).VecEqual(new Vec2(-4, -6));
});

test("Scale by 0", () => {
let v = new Vec2(2, 3);
let s = Mat2.Scale(0);
expect(s.times(v)).VecEqual(new Vec2(0, 0));
});
});
  1. File name and location: You should name your file as xxx.test.js and put them under the Assignment0_CS4620/src/Tests/ folder.
  2. Use describe to group your large test section together
  3. Write your unit test inside a test function.
  4. Use expect combined with a certain comparison function like toBe, toEqual to make assertions. (We have provided you with customed comparison functions like VecEqual and MatrixEqual. You can check out more in Assignment0_CS4620/src/Tests/helpers/TestHelpers.js)

How to run unit tests?​

Run in terminal​

  1. First check that all dependencies are installed by running yarn install. If there's any dependency that is not installed, running yarn install will install it. It may take a few mimutes the first time you run yarn install. After that first install, you don't need to run yarn install any more before you run tests.
  2. Run yarn test to run all tests.