2019-05-01+Web+Designer+UK

(Brent) #1

TestyourJSwith the Jest framework


Tutorials


15. Find the snapshot file
When Jest encounters a new snapshot-related
object, the runner generates an additional snapshot
file and displays the message shown in the figure
accompanying this step. As our object contains a
randomly generated value, subsequent executions
of the test suite will (usually) fail with date and
ID mismatches.

tamhan@TAMHAN14:~/YARNspace/__snapshots__$ ls
tam.test.js.snap
// =============== FILE gedit tam.test.js.snap
===============
// Jest Snapshot v1, goo.gl/fbAQLP
exports[`is a small test 1`] = `
Object {
'createdAt':2019-03-07T09:03:37.980Z,
'id':12,
'name': 'Tam HANNA',
}
`;

16 .Limitanalysisaccuracy
Onewaytoworkaroundtheprobleminvolvesthe
useof‘scoped’matchers.Theydifferfromtheir
normalcolleaguesinthattheyacceptanyvalueofa
giventype— inourcase,bothcreatedAtandid
shouldbehandledbythesesmartelements.

expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
id: expect.any(Number),
});
});

17 .Updatethesnapshotfile
Sadly,runningtheprograminthecurrentstatedoes
notimproveoursituation.Thisis logical,asthe
snapshotfilesarestilloutofdate.Simplyenter‘YARN
test-u’andlookattheupdatedcontents.The-u
commandcanalsobeusedtoupdateoutdated
snapshotsingeneral— keepinmindthatJestwill
considerwhatevervaluesit mayfindduringthe
testexecution.

// Jest Snapshotv1, goo.gl/fbAQLP
exports[`is a small test1`] = `

18

15

Object{
'createdAt':Any<Date>,
'id': Any<Number>,
'name': 'TamHANNA',
}
`;

18 .Createa configurationfile
Jestis notlimitedtoworkingwiththedefault
environmentsettings.InvokingJest--initfrominside
theYARNenvironmentlaunchestheset-upwizard
showninthefigureaccompanyingthisstep.It allows
youtosetupvariousoptionsrelatedtothetest
executionenvironment.

19 .Asyncwaiting
JavaScriptunittestframeworksusuallyhavea hard
timerunningunittestsagainstasynchronouscode.
Jeststandsoutinthatit accommodateswaitingfor
you— intheexamplebelow,thedonecallbackcan
beusedto‘wait’fora result:

test(‘the datais peanutbutter’, done=> {
function callback(data) {
expect(data).toBe(‘peanut butter’);
done();

}
fetchData(callback);
});

20. Use mock functions
Another extremely useful feature involves the use of
mock functions. They can be submitted in place of a
callback, and return data about the invocations.

const mockCallback = Jest.fn(x => 42 + x);
forEach([0, 1], mockCallback);
// The mock function is called twice
expect(mockCallback.mock.calls.length).toBe(2);
// The first argument of the first call to the
function was 0
expect(mockCallback.mock.calls[0][0]).toBe(0);

21. Learn more
Jest is an extremely complex framework which can
not be covered in a single issue of Web Designer.
Visit Jestjs.io/docs/’Jestjs.io/docs/ on a non-Mozilla
browser to find out more about the possibilities
related to frameworks such as React.

82 ��������������������������������������������������tutorial

Free download pdf