How do I loop through dynamic test cases in Jest?

我有下面这样的测试用例,如何使用it/test个方法动态创建jest测试用例.

然而,它只是通过了测试,没有执行循环中的测试用例.

    const mymodule = require('mymodule');

    const testCases = [
        {q: [2, 3],r: 5},
        {q: [1, 2],r: 3},
        {q: [7, 0],r: 7},
        {q: [4, 4],r: 8}
    ];

    describe("Test my Math module", () => {
        test("test add method", () => {
            for (let i = 0; i < testCases.length; i++) {
                const { q,r } = testCases[i];
                it(`should  add ${q[0]},${q[1]} to ${expected}`, () => {
                    const actual = mymodule.add(q[0] + q[1]);
                    expect(actual).toBe(expected);
                });
            }
        });
    
    });

推荐答案

有一种内在的方法可以做到这一点:test.each(table)(name, fn, timeout)

例如

test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(
  '.add(%i, %i)',
  (a, b, expected) => {
    expect(a + b).toBe(expected);
  },
);

其中,2D数组中的每个内部数组都作为参数传递给测试函数.

Node.js相关问答推荐

利用Gemini:通过Vertex AI还是通过Google/generative-ai?

如何使用NodeJS处理来自请求的单个或多个文件?

无法生成仅具有生产依赖项的 node 类型脚本项目

谷歌应用程序脚本UrlFetchApp和nodejs-axios返回不同的结果;MyFitnessPal日记

无法将示例 Node.js 应用程序部署到 AWS Elastic Beanstalk

未授权使用联合身份未授权用户角色从 Amplify graphQL 访问类型 Y 上的 X

为什么当我try req.logout() 时出现此错误?

使用 Node.js 在 MongoDB 中搜索

Mongoose-更新嵌套数组

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

tsc:当我上传 React+next js 和 node 项目时,在 heroku 找不到

eslint - vscode 的可选链接错误

我应该在(Docker)容器中使用 forever/pm2 吗?

分块 WebSocket 传输

使用 NodeJS 将新对象附加到 DynamoDB 中的 JSON 数组

webpack css-loader 在外部样式表的 url() 引用中找不到图像

如何从 npm 注册表中删除 npm 包?

如何仅在丢失的路由上将 Express.js 设置为 404?

yarn 和 npm 的主要区别是什么?

将 expressjs 绑定到特定的 IP 地址