Search code examples
javascriptjestjsbind

Jest Test function bind


How can one bind s.th. to the test function executed by jest?

I want to run the same set of tests twice for different configs, like this:

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)
});

But this is undefined when run by jest.


Solution

  • Turns out jest provides a built-in helper to do exactly this:

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