首页 > 解决方案 > Jest 测试函数绑定

问题描述

一个人怎么能绑定s.th。到 jest 执行的测试函数?

我想为不同的配置运行同一组测试两次,如下所示:

function wrap(title, fn) {
    [1,2].forEach(x => {
        this.hello = x
        fn.bind(this)
        fn() // works
        test(title, fn) // does not work
    })
}

wrap('test hello world', function() {
    console.log('this.hello', this.hello)
});

但是thisundefined开玩笑的时候。

标签: javascriptjestjsbind

解决方案


原来 jest 提供了一个内置的助手来做到这一点:

describe.each([1,2])('test', x => {
    test(`test ${x}`, function() {
        console.log('x', x)
    });
})

推荐阅读