jestjs - 如何在异步 Jest 测试中传入 done() 参数。每个案例

标签 jestjs ts-jest

我正在尝试编写一个测试异步方法的 Jest 测试用例,我想传入 done()参数所以 jest 在结束测试之前等待它被触发,但是,我不确定把它放在哪里。
有任何想法吗?

const testcases = [
        [
            'Crew',
            [1,2,3],
            Enum.Level1
        ],
        [
            'Staff',
            [4,5,6],
            Enum.Level2
        ]
    ];
test.each(testcases )(
        'Should be able to load differing cases %p',
        (
            typeName: string,
            initalVals: string[],
            type: LevelType
        ) => {
            // some call that updates mobx store state

            when(
                () => mobxstoreProperty.length == initalVals.length,
                () => {
                    // my assertions

                    done();
                }
            );
        }
    );
对于单个 Jest 测试,我可以这样做:
test('my single test', done => {
  // some call that updates mobx store state

     when(
       () => mobxstoreProperty.length == initalVals.length,
       () => {
         // my assertions
         done();
       }
    );
});
只是不确定在我使用 test.each 时该怎么做方法。

最佳答案

我使用命名参数,我可以添加 done()方法作为最后一个函数参数。例如像这样:

const testcases: {
    typeName: string;
    initalVals: string[],
    type: LevelType
}[] = [
    {
        typeName: 'Crew',
        initalVals: [1,2,3],
        type: Enum.Level1
    },
    {
        typeName: 'Staff',
        initalVals: [4,5,6],
        type: Enum.Level2
    },
];
test.each(testcases)(
    'Should be able to load differing cases %p',
    // Must use `any` for `done`, as TypeScript infers the wrong type:
    ({typeName, initalVals, type}, done: any) => {
        // some call that updates mobx store state
        when(
            () => mobxstoreProperty.length == initalVals.length,
            () => {
                // my assertions

                done();
            }
        );
    }
);

我还没有测试你是否可以添加 done()方法作为带有数组参数的最后一个参数,但也许这也有效。

关于jestjs - 如何在异步 Jest 测试中传入 done() 参数。每个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59940440/

相关文章:

jestjs - 在 GitLab CI 上使用 Playwright 时出现 WebSocket 错误

typescript - TS-Jest 无法解析 tsconfig 路径

angular - TypeError : configSet. processWithEsbuild 不是函数

javascript - <AnimatedComponent/> 的快照测试在 react native 和 Jest 中失败

reactjs - React 测试库测试错误 `NaN` 是 `left` css 样式属性的无效值

javascript - Jest 对调用返回 Promise 的函数的函数进行单元测试

reactjs - 使用 Jest 时是否有另一种方法来模拟组件的 mapDispatchToProps

javascript - 如何模拟非异步方法以使用 Jest 抛出异常?

typescript - Visual Studio代码无法正确踩入TypeScript代码

javascript - 如何检查嵌套 Jest 模拟函数中是否调用了方法