logo
🛠️ 开发工具

Jest

Jest Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 开发工具🧭 Markdown 速查🏷️ 2 个标签
#jest#testing
向下滚动查看内容
返回全部 Cheat Sheets

A Quick Overview to Jest

Jest is a delightful JavaScript testing framework maintained by Facebook. It is widely used for unit testing, integration testing, and even end-to-end testing in modern JavaScript and Node.js applications. Jest comes with a powerful set of features, including a built-in test runner, assertion library, mocking utilities, snapshot testing, and test coverage reporting.

This guide targets Jest v20 and gives a concise yet practical overview of how to use it effectively.

Key Concepts Explained
  • describe(): Used to group related test cases into a test suite.
  • test() / it(): Define a single test case. it() is just a BDD-style alias for test().
  • expect(): Assertion library that checks whether a value meets expectations.
  • beforeEach() / afterEach(): Runs code before or after every test in a suite.
  • beforeAll() / afterAll(): Runs setup/teardown code once before or after all tests.
  • .only / .skip: Focus or ignore specific tests/suites.
  • Snapshot testing: Captures the rendered output and compares it across test runs.
  • Mock functions: Simulate function behavior or monitor how functions are called.
  • Timer mocks: Test time-based behavior like setTimeout() and setInterval().
  • Async testing: Write tests that handle Promises or async/await.

🚀 Quick Start
BASH
滚动查看更多
npm install --save-dev jest babel-jest

Add this to your package.json:

JSON
滚动查看更多
"scripts": {
  "test": "jest"
}

Run your tests:

BASH
滚动查看更多
npm test -- --watch

📖 See: Getting Started


✍️ Writing Tests

JS
滚动查看更多
describe('My work', () => {
	test('works', () => {
		expect(2).toEqual(2);
	});
});
  • describe: Group related tests.
  • test or it: Define individual test cases.
  • expect: Make assertions.

🔄 it() is an alias for test().


🔧 Setup Hooks

Use these for setup/teardown routines:

JS
滚动查看更多
beforeEach(() => { ... });
afterEach(() => { ... });
beforeAll(() => { ... });
afterAll(() => { ... });

🎯 Focusing or Skipping Tests

Focusing tests:

JS
滚动查看更多
describe.only(...);
it.only(...); // or fit()

Skipping tests:

JS
滚动查看更多
describe.skip(...);
it.skip(...); // or xit()

🏁 Optional CLI Flags

FlagDescription
--coverageShow test coverage summary
--detectOpenHandlesDetect unclosed handles (e.g., sockets)
--runInBandRun tests serially (useful for CI)

✅ Expectations (Matchers)

Basic
JS
滚动查看更多
expect(value).not.toBe(value);
expect(value).toEqual(value);
expect(value).toBeTruthy();

Note: toEqual performs deep equality.

Snapshots
JS
滚动查看更多
expect(value).toMatchSnapshot();
expect(value).toMatchInlineSnapshot();

Inline snapshots require Prettier.

Errors
JS
滚动查看更多
expect(fn).toThrow(error);
expect(fn).toThrowErrorMatchingSnapshot();
Booleans
JS
滚动查看更多
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeTruthy();
expect(value).toBeUndefined();
expect(value).toBeDefined();
Numbers
JS
滚动查看更多
expect(value).toBeCloseTo(number, digits);
expect(value).toBeGreaterThan(number);
expect(value).toBeLessThanOrEqual(number);
Objects
JS
滚动查看更多
expect(value).toBeInstanceOf(Class);
expect(value).toMatchObject(obj);
expect(value).toHaveProperty('key', value);
Arrays/Strings
JS
滚动查看更多
expect(value).toContain(item);
expect(value).toHaveLength(number);
expect(value).toMatch(/pattern/);
Custom Matchers
JS
滚动查看更多
expect.extend(customMatchers);
expect.any(Constructor);
expect.assertions(1);

⏱️ Async Tests

Promises
JS
滚动查看更多
test('resolves correctly', () => {
  return somePromise().then(data => {
    expect(data).toEqual(...);
  });
});
Async/Await
JS
滚动查看更多
test('awaits correctly', async () => {
  const result = await asyncFunc();
  expect(result).toBe(...);
});

📖 See: Jest Async Testing


📸 Snapshot Testing

JS
滚动查看更多
it('renders correctly', () => {
	const output = something();
	expect(output).toMatchSnapshot();
});

For React components:

JS
滚动查看更多
import renderer from 'react-test-renderer';

it('matches snapshot', () => {
	const tree = renderer.create(<Component />).toJSON();
	expect(tree).toMatchSnapshot();
});

⏲️ Timers

JS
滚动查看更多
jest.useFakeTimers();

it('delays call', () => {
	jest.runOnlyPendingTimers();
	jest.runAllTimers();
});

📖 See: Timer Mocks


🧪 Mock Functions

Creating Mocks
JS
滚动查看更多
const fn = jest.fn();
const squared = jest.fn(n => n * n);
Assertions
JS
滚动查看更多
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledWith(arg1, arg2);
Flexible Matchers
JS
滚动查看更多
expect(fn).toHaveBeenCalledWith(expect.any(String));
expect(fn).toHaveBeenCalledWith(expect.arrayContaining([1, 2]));
Instances
JS
滚动查看更多
const MyClass = jest.fn();
const a = new MyClass();
const b = new MyClass();
MyClass.mock.instances; // [a, b]
Call Data
JS
滚动查看更多
fn.mock.calls.length;
fn.mock.calls[0][0];
Return Values
JS
滚动查看更多
jest.fn().mockReturnValue('hello');
jest.fn().mockReturnValueOnce('hi');
Mock Implementations
JS
滚动查看更多
const fn = jest
	.fn()
	.mockImplementationOnce(() => 1)
	.mockImplementationOnce(() => 2);

This comprehensive guide helps you get started with Jest testing or use it like a pro. It pairs perfectly with the React Testing Library for a user-centric testing workflow.

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572