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
- group tests together (e.g.
describe()
) - declare a unit test (e.g.
test()
) - make assertions (e.g.
expect().toBe()
,expect().toEqual()
)
Jest allow us to easily
- name our unit tests
- group and run them together
- see how many tests we have successed and failed
- 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:
Assignment0_CS4620/src/Tests/Scratch.test.js
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));
});
});
- File name and location: You should name your file as
xxx.test.js
and put them under theAssignment0_CS4620/src/Tests/
folder. - Use
describe
to group your large test section together - Write your unit test inside a
test
function. - Use
expect
combined with a certain comparison function liketoBe
,toEqual
to make assertions. (We have provided you with customed comparison functions likeVecEqual
andMatrixEqual
. You can check out more inAssignment0_CS4620/src/Tests/helpers/TestHelpers.js
)
How to run unit tests?​
Run in terminal​
- First check that all dependencies are installed by running
yarn install
. If there's any dependency that is not installed, runningyarn install
will install it. It may take a few mimutes the first time you runyarn install
. After that first install, you don't need to runyarn install
any more before you run tests. - Run
yarn test
to run all tests.