Jest: Add support for ES6 generator

Created on 22 Jan 2017  ยท  10Comments  ยท  Source: facebook/jest

I am trying to test a generator function someFunc*() as follows.

describe('generator test', () => {
  it('should call generator function', function *() {
      var data = yield someFunc()

      expect(data).toBe(3);
  });
});

The test fails with this message:

Jest: `it` must return either a Promise or undefined.

Most helpful comment

+1
As a workaround I'm using co to wrap the generator with a function that returns a promise:

import co from 'co';
describe('generator test', () => {
  it('should call generator function', co.wrap(function *() {
      var data = yield someFunc()

      expect(data).toBe(3);
  }));
});

All 10 comments

What if you try this approach?

describe('generator test', () => {
  it('should call generator function', function() {
      var data = someFunc()

      expect(data.next().value).toBe(3);
  });
});

We are not adding support for this.

@cpojer This is sucks, because I use redux-saga.

FAIL  __tests__/index.android.js
  โ— Test suite failed to run

   /app/redux/saga/auth.js: Unexpected token (58:20)
        56 |   try {
        57 |     const { email, password, name } = action.payload;
      > 58 |     const payload = yield call(Client.register, email, password, name);
           |                     ^
        59 |
        60 |     yield put(AuthActions.user(payload));
        61 |   } catch (error) {

Maybe exists some options how to resolve this problem?

It seems like you aren't properly transforming generators in this example, this is not a Jest error.

@cpojer Generator Function is short code and easy to read. async/await is similar to it, but it's still early. Why don't you support this? This will be one reason for using ava.

+1
As a workaround I'm using co to wrap the generator with a function that returns a promise:

import co from 'co';
describe('generator test', () => {
  it('should call generator function', co.wrap(function *() {
      var data = yield someFunc()

      expect(data).toBe(3);
  }));
});

Hello @cpojer, what is your suggestion for testing generator functions ?
What is the Jest setup you recommend ?

Thanks in advance.

Solution:
1 - add to package.json into jest section:
"jest": { "setupTestFrameworkScriptFile": "<rootDir>/testing/test-bundler.js" },
2 - create file '/testing/test-bundler.js' with content:
// needed for regenerator-runtime import 'babel-polyfill';

It's all!

Generators are now part of javascript. Why is this outside the scope of what is supported?

This is now implemented, but not released.

5166

Was this page helpful?
0 / 5 - 0 ratings