推荐答案
-- -------------------- ---- ------- -- -------------- -------- ------ -- - ------ - - -- - -- ---- ---- ---------- - - - -- ----- --- -- -- - ------------- ------------ ---展开代码
本题详细解读
1. 安装 Jest
首先,确保你已经安装了 Jest。可以通过 npm 或 yarn 来安装:
npm install --save-dev jest
或者
yarn add --dev jest
2. 创建测试文件
在项目中创建一个测试文件,通常命名为 *.test.js
或 *.spec.js
。例如,add.test.js
。
3. 编写测试用例
在测试文件中,使用 test
或 it
函数来定义一个测试用例。test
和 it
是等价的,可以根据个人喜好选择。
test('adds 1 + 2 to equal 3', () => { expect(add(1, 2)).toBe(3); });
4. 使用 expect
和匹配器
expect
函数用于断言测试结果。Jest 提供了多种匹配器(matchers)来验证不同的条件。例如:
toBe(value)
:用于比较原始值或对象引用。toEqual(value)
:用于深度比较对象或数组的内容。toBeTruthy()
:用于检查值是否为真。toBeFalsy()
:用于检查值是否为假。
5. 运行测试
在 package.json
中添加一个脚本来运行 Jest:
{ "scripts": { "test": "jest" } }
然后运行以下命令来执行测试:
npm test
或者
yarn test
6. 测试覆盖率
Jest 还支持生成测试覆盖率报告。可以通过以下命令生成覆盖率报告:
npm test -- --coverage
或者
yarn test --coverage
7. 异步测试
Jest 支持异步测试。可以使用 async/await
或返回 Promise 的方式来测试异步代码。
test('async test', async () => { const result = await someAsyncFunction(); expect(result).toBe('expected value'); });
8. Mock 函数
Jest 提供了强大的 Mock 功能,可以用来模拟函数、模块或类的行为。
const mockFn = jest.fn(); mockFn.mockReturnValue(42); test('mock function', () => { expect(mockFn()).toBe(42); });
9. 测试生命周期钩子
Jest 提供了 beforeEach
、afterEach
、beforeAll
和 afterAll
等钩子函数,用于在测试前后执行一些操作。
beforeEach(() => { // 在每个测试之前执行 }); afterEach(() => { // 在每个测试之后执行 });
10. 测试环境
Jest 支持在 Node.js 和浏览器环境中运行测试。可以通过配置 testEnvironment
来指定测试环境。
{ "jest": { "testEnvironment": "node" } }
或者
{ "jest": { "testEnvironment": "jsdom" } }