2019-05-01+Web+Designer+UK

(Brent) #1
{
returna+b;
}
function divide(a,b)
{
returna/b;
}
module.exports = sayHello;

6 ....andtestit
A lookattheerroroutputshowsthatJestusesthe
expression‘**/��tests��/**/*.[jt]s?(x),**/?(*.)+(spec|test).
[tj]s?(x)‘ tofindtestcandidates.
Thus,a smarttestfilewouldbecalledtam.test.js
— fornow,thesimplecontentshowninthecode
accompanyingthisstepshallsuffice.

const tam = require(‘./tam’);
test(‘Checks if Tam is friendly’,() => {
expect(tam()).toBe('Hello');
});

TestyourJSwith the Jest framework


7. Understand the situation at hand
Jest expects test cases to be provided in dedicated
files. Due to the product being targeted at modern
object-oriented code bases, the code to be tested
usually comes in the shape of a module. The actual
value comparison is then performed using matchers
that are similar to other frameworks.

8. Run the test
Finally, order another execution of the test cases via
the YARN package manager. It will yield the results
shown in the accompanying figure — as our test
case is simple, execution is accomplished quickly.

tamhan@TAMHAN14:~/YARNspace$ YARN test
YARN run v1.13.0
$ Jest
PASS ./tam.test.js

9. Structured test execution
Some tests can only be run after a more or less
elaborate set-up routine has run its course. Jest
accomplishes this via the before and after function.
A beforeEach call runs before each test case. A
beforeAll method is run once the test suite starts up.

beforeEach(()=> {
initializeCityDatabase();
});
afterEach(()=> {
clearCityDatabase();
});

Floating point


trouble
Ifyouever find yourself wanting a specific
precision, feel free to use dedicated maths libraries.
Theseproducts use integers to emulate floating
numbers – a slow but arbitrarily accurate process.

Tutorials


beforeAll(()=> {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});

10. A surprising situation
Now that our strings check out, it is time to test the
arithmetic functions. For that, the exports of tam.js
need to be adjusted. The following two test cases
are ready to fail, with the result shown in the figure.

module.exports.add = add;
module.exports.divide = divide;
const tam = require(‘./tam’);
test(‘Checksif we can add’, () => {
expect(tam.add(2,2)).toBe(4);
});
test(‘Checksif we can divide’, () => {
expect(tam.divide(1,3)).toBe(0.333333333);
});

11. Account for imprecisions
Like most other programming languages, the
JavaScript runtime uses floating number
mathematics. This means that non-integer numbers
cannot always be expressed with infinite accuracy.
Working around the problem requires the use of a
different matcher. When dealing with floating
numbers, using toBe is generally not advised.

8

80 �������������������������������������������������tutorial

Free download pdf