Jest Test Framework Quick Reference

This page is intended for my own quick reference when working with Jest and refreshing my memory on core concepts. I may extend this to include Enzyme at some point as well, or maybe I will dedicate that to a separate post.

Building blocks of a Jest test file

describe('',()=>{}) // test suites
it('',()=>{})       // individual tests
expect()   // steps that must be satisfied for entire test to pass
describe('A Sweet Test Suite', () => {
    it('Does something that I expect', () => {
         // there are many different "matchers" 
         // ie: variations of expect()
         expect(someVariable).toBe(someValue);
    });
});

Matchers

Matchers test that existing variables equal expected values. Most possibilities are listed below:

expect(x).toBe(y)            // NOTE: Exact equality (not just value)
expect(x).toEqual(y)         // Like above, except equates value

// Truthy-ish checks. These all have opposites too
// eg: .toBeDefined() 
// But a simple .not.toBeUndefined() will achieve the same effect
expect(x).toBeNull();
expect(x).toBeUndefined();
expect(x).toBeTruthy();

expect(x).toBeGreaterThan(y);
expect(x).toBeGreaterThanOrEqual(y);
expect(x).toBeLessThan(y);
expect(x).toBeLessThanOrEqual(y);

expect(x).toMatch(stringMatcher);
expect(someArray).toContain(element);

expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(Error);
// Exact error message matching:
expect(compileAndroidCode).toThrow('Custom error message.');

expect(x).not // negation for any of the above

Leave a Reply

Your email address will not be published. Required fields are marked *