Review core JavaScript syntax and context through testing functions
Our tests.js
file has access to a new built-in, QUnit
and we will be using
the QUnit.test
method which will be assigned to a test
variable.
We will also be using the expect
built-in that will be passed to our testing function
The structure of a test is very similar to the use of addEventListener
!
// only once at top of file:
const test = QUnit.test;
// Each test case
test('test name', (expect) => {
});
Part | Purpose |
---|---|
test |
Built-in QUnit testing method |
'test name' |
Descriptive test name |
(expect) => {...} |
Function (arrow function) that will be called by qUnit to run the test |
test('demo: adds two numbers', (expect) => {
//Arrange
// Set up your arguments and expectations (inputs and outputs)
const x = 2;
const y = 5;
const expected = 7;
//Act
// Call the function you're testing and set the result to a const
const actual = add(x, y);
//Expect
// Make assertions about what is expected versus the actual result
expect.equal(actual, expected);
});
Part | Purpose |
---|---|
// Arrange |
What are the inputs and outputs? |
// Act |
Run the function being tested! |
// Assert |
Validate by asserting something is true |
Write your tests and corresponding functions one feature at a time. Don't stub out all the functions and imports!
Add the export
keyword in front of your declared function definition:
export function add(x, y) {
return x + y;
}
Use the following syntax to import the functions from the other file:
import {
add,
subtract,
areaOfTriangle,
} from './functions.js';
For each function feature:
- Read description, ask questions if not understood
- Identify function inputs and output
- Identify number of test cases required
- Start with first test
- Decide on name for test and for function
- Add empty test in
tests.js
- Create and
export
empty function infunctions.js
and import intotests.js
- Write test:
- Translate inputs and outputs into "Arrange" variables,
- write the "Act" function call
- modify "Assert" if needed
- Add parameters to function, write code to make pass
- Implement additional tests if required (using same function)