2019-05-01+Web+Designer+UK

(Brent) #1

Test your JS with the Jestframework


ofrequiredattributes.Jest’slogictakesthe
snapshot’scontentsandperformsananalysis
againsttheobjectreturned— errorswillberaisedif
a mismatchis detected.Forthefollowingsteps,
startoutbyplacingthecodeshownnexttothis
stepinsideoftam.test.js.

it(‘is a small test’,() => {

test(‘Checksif we can divide’, () => {
expect(tam.divide(1,3)).
toBeCloseTo(0.333333333);
});


  1. Run just one
    Should you ever feel like running one test, feel free
    to use the test.only function. It informs the runner
    that all other test cases are to be ignored — helpful
    and time-saving as your unit test suites grow.


test.only(‘this will be the only test that
runs’,
() => {
expect(true).toBe(false);
});



  1. Understanding snapshots
    As JavaScript object orientation entered mainstream
    developer conscience, more and more code
    adopted OOP principles.
    Sadly, verifying the correctness of objects gets
    tedious quickly — checking each and every
    member’s value by hand leads to long and
    difficult-to-handle test code.




  2. Content analysis
    Think of snapshots as a template containing a set




Jesttestscanalso
berunoutsideofa
package manager.
In this case, the Jest
command line utility
must be used — it
can only be run when
installed globally using
either NPMs or YARN’s
global install feature.
Once installed, visit
Jestjs.io/docs/en/cli.
Jest’s developer
team provide command
line users with dozens
of options intended to
tailor execution scope
to the needs of the task
at hand.
Entering ‘Jest
--findRelatedTests
path/to/fileA.js path/
to/fileB.js’ runs only
those tests which touch
the content of the files
passed in as arguments.
In addition to that, the
command line tool
can even analyse
local repositories and
run only these tests
affected by currently
uncommitted code.

Harness the
power of the
command line

Tutorials


const user= {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: ‘Tam HANNA’,
};
expect(user).toMatchSnapshot();
});

14

tutorial ������������������������������������������������� 81
Free download pdf