3.9 KiB
3.9 KiB
title | category | layout | updated | weight |
---|---|---|---|---|
Jest | JavaScript libraries | 2017/sheet | 2017-08-26 | -3 |
Testing
{: .-three-column}
Quick start
{: .-prime}
npm install --save-dev jest babel-jest
/* Add to package.json */
"scripts": {
"test": "jest"
}
{: .-setup}
# Run your tests
npm test -- --watch
{: .-setup}
See: Getting started
Writing tests
describe('My work', () => {
test('works', () => {
expect(2).toEqual(2)
})
})
BDD syntax
describe('My work', () => {
it('works', () => {
···
})
})
it
is an alias for test
.
See: test()
Asynchronous tests
test('works with promises', () => {
return new Promise((resolve, reject) => {
···
})
})
test('works with async/await', async () => {
const hello = await foo()
···
})
Return promises, or use async/await. See: Async tutorial
Setup
beforeEach(() => { ... })
afterEach(() => { ... })
beforeAll(() => { ... })
afterAll(() => { ... })
See: afterAll() and more
Focusing tests
describe.only(···)
it.only(···) // alias: fit()
See: test.only
Skipping tests
describe.skip(···)
it.skip(···) // alias: xit()
See: test.skip
Expect
{: .-three-column}
Basic expectations
expect(value)
.not
.toBe(value)
.toEqual(value)
See: expect()
Snapshots
expect(value)
.toMatchSnapshot()
Errors
expect(value)
.toThrow(error)
.toThrowErrorMatchingSnapshot()
Booleans
expect(value)
.toBeFalsy()
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toBeDefined()
Numbers
expect(value)
.toBeCloseTo(number, numDigits)
.toBeGreaterThan(number)
.toBeGreaterThanOrEqual(number)
.toBeLessThan(number)
.toBeLessThanOrEqual(number)
Objects
expect(value)
.toBeInstanceOf(Class)
.toMatchObject(object)
.toHaveProperty(keyPath, value)
Objects
expect(value)
.toContain(item)
.toContainEqual(item)
.toHaveLength(number)
Strings
expect(value)
.toMatch(regexpOrString)
Others
expect.extend(matchers)
expect.any(constructor)
expect.addSnapshotSerializer(serializer)
expect.assertions(1)
More features
Snapshots
const tree = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>
).toJSON()
// First run creates a snapshot; subsequent runs match it
expect(tree).toMatchSnapshot()
# To update snapshots
jest --updateSnapshot
Mocks
const fn = jest.fn()
const fn = jest.fn(n => n * n)
expect(fn)
// Functions
.toHaveBeenCalled()
.toHaveBeenCalledTimes(number)
.toHaveBeenCalledWith(arg1, arg2, ...)
.toHaveBeenLastCalledWith(arg1, arg2, ...)
.toHaveBeenCalledWith(expect.anything())
.toHaveBeenCalledWith(expect.any(constructor))
.toHaveBeenCalledWith(expect.arrayContaining([ values ]))
.toHaveBeenCalledWith(expect.objectContaining({ props }))
.toHaveBeenCalledWith(expect.stringContaining(string))
.toHaveBeenCalledWith(expect.stringMatching(regexp))
Timers
jest.useFakeTimers()
it('works', () => {
jest.runOnlyPendingTimers()
jest.runTimersToTime(1000)
jest.runAllTimers()
})
See: Timers
References
{: .-one-column}
- Based on Jest v19.
- http://facebook.github.io/jest/ {: .-also-see}