发布于 2026-01-06 1 阅读
0

使用 Jest 和 async/await 进行测试 目录 测试异步函数 测试错误处理 亲自尝试 依赖项 亲自尝试 贡献 工具 更多资源

使用 Jest 和 async/await 进行测试

目录

测试异步函数

测试错误处理

你自己试试看

依赖关系

试试看

贡献

工具

更多资源

如果你读过我之前的帖子(使用内存数据库测试 Node.js + Mongoose),你就会知道,在过去的几周里,我一直在测试一个 node.js 和 mongoose 应用程序。

我非常喜欢 JavaScript 中的 async/await。毕竟,我见识过回调地狱,那可不是什么好景象。所以很自然地,当我开始编写测试时,会遇到很多需要测试的异步代码,也因此遇到了一些问题,我必须解决这些问题才能让我的测试正常运行。

在这篇文章中,我将分享一些实际的例子,帮助你使用 Jest 测试你的异步 JavaScript 代码

目录

测试异步函数

以下是异步代码测试套件的示例:

describe('scope ', () => {
    it('works with async', async () => {
        /* Some async code testing. */
    });
});
Enter fullscreen mode Exit fullscreen mode

请注意,内部的函数describe不是async,但外部的函数it是。

先放入一些数据进行测试

有时我们需要预先填充测试数据库,以便有一些数据可供使用。我将向您展示两种实现方法:

a. 在每个测试中添加所需数据

请检查以下代码:

it('should retrieve the correct product if id matches', async () => {
    // Seed.
    const createdIphone = await productModel.create(productIphone);

    // test
    const foundProduct = await productService.getById(createdIphone.id);

    expect(foundProduct.id).toBe(createdIphone.id);
    expect(foundProduct.name).toBe(productIphone.name);
});
Enter fullscreen mode Exit fullscreen mode

测试开始时会预先设置数据,并在后续测试中使用。这种方法适用于只需要特定数据进行特定测试的情况。如果您发现自己需要在其他测试中复制粘贴第一行代码,请考虑以下方法。

b. 使用beforeEach对数据进行初始化。

beforeEach()与其在每个测试中都添加数据,不如像这样直接在方法内部添加:

beforeEach(async () => await createProducts());
afterEach(async () => await dbHandler.clearDatabase());

describe('product ', () => {
    it('test that needs data', async () => {

    });

    it('another test that needs data', async () => {

    });
});
Enter fullscreen mode Exit fullscreen mode

这样,产品将在每次测试前添加,并在每次测试后移除,从而确保每次测试都有一个干净的开始。

先等等期待

由于我们使用了 `wait()` 函数,async我们可以等待函数的结果,然后使用 `wait()` 函数expect来验证结果,如下所示:

it('should retrieve the correct product if id matches', async () => {
    const foundProduct = await productService.getById(productIphoneId);

    expect(foundProduct.id).toBe(productIphoneId);
    expect(foundProduct.name).toBe(productIphone.name);
});
Enter fullscreen mode Exit fullscreen mode

使用resolve来等待结果

另一种测试异步函数结果的方法是使用 `--wait`,resolves这将导致 Jest 等待异步函数执行完毕。

在以下示例中,我们等待getById问题解决,然后检查结果是否为空:

it('should return null if nothing is found', async () => {
    // mongoose.Types.ObjectId() generates a new ID that won't exist in the current database.
    await expect(productService.getById(mongoose.Types.ObjectId()))
        .resolves
        .toBeNull();
});
Enter fullscreen mode Exit fullscreen mode

测试错误处理

测试函数是否抛出错误

我们可以期望异步函数不会抛出错误,如下所示:

it('can be created correctly', async () => {
    expect(async () => await productService.create(productComplete))
        .not
        .toThrow();
});
Enter fullscreen mode Exit fullscreen mode

测试函数是否抛出正确的错误。

我们可以使用rejects等待异步函数解析并返回错误,然后结合使用toThrow以确保抛出的错误是我们期望的错误。

it('requires name and price', async () => {

    await expect(productService.create(productMissingName))
        .rejects
        .toThrow(mongoose.Error.ValidationError);

    await expect(productService.create(productMissingPrice))
        .rejects
        .toThrow(mongoose.Error.ValidationError);
});
Enter fullscreen mode Exit fullscreen mode

你自己试试看

这里有一个Github代码库,我把本文中包含的所有示例都放在里面了:

GitHub 标志 pawap90 / test-mongoose-inmemory

一个示例项目,演示如何使用 Jest 和内存数据库测试 Mongoose 操作。

这是一个 Node.js + Mongoose + Jest 示例项目,演示了如何使用 Jest 和内存数据库测试 mongoose 操作

这个仓库是我为文章《使用内存数据库测试 Node.js + Mongoose》而构建的示例

依赖关系

运行此项目需要以下条件:

  • Node.js

(由于该软件包会在内存中运行,因此不需要 MongoDB mongodb-memory-server。)

试试看

1. 安装依赖项

npm install

2. 运行测试

npm test

贡献

欢迎您在 Issues 部分留言或提交 PR,为本项目做出贡献。更多更多样化的测试示例总是很有帮助的。请务必查看 Jest 文档和现有示例,以避免重复劳动。

工具

本项目使用的主要工具:

另外,还可以查看mongodb-memory-server-global,以便全局下载 mongod 的二进制文件……





我为之前的文章创建了这个仓库,但为了这篇文章,我对其进行了改进并添加了更多示例。

更多资源

文章来源:https://dev.to/paulasantamaria/testing-with-jest-async-await-314e