Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: Testing generator function which yields another generator function

I have a function which looks like this

export function* login(user, page) {
        yield checkIp();
        return yield loginAuth(user, page);
 }

I am trying to test the login generator from unit test as below

it('login test', () => {
  const user = { email:"[email protected]", password:"1234" }
 const generator = login (user, {});
 generator.next();
 expect(generator.return().done).toEqual(true); });

Is this the right way to do it? Also in the coverage, I am not able to cover the return statement from the login generator function. Any help would be much appreciated.

Also this is my first time posting here, forgive me if I didn't follow the rules correctly.

like image 836
Humourprogrammer Avatar asked Dec 19 '17 23:12

Humourprogrammer


1 Answers

Update 2021: Jest now supports generator functions out of the box.

You can test your generator functions with Jest using one of these two approaches:

Approach 1:

Test the next value of generator directly:

describe('generator test', () => {
  it('should call generator function', function() {
      const user = { email:"[email protected]", password:"1234" };
      const generator = login(user, {});

      expect(generator.next().value).toBe(SOME_VALUE_HERE));
  });
});

Approach 2:

You can use co package which wraps your generator in promise which is supported in Jest.

import co from 'co';

describe('generator test', () => {
  it('should call generator function', co.wrap(function *() {
      const user = { email:"[email protected]", password:"1234" };
      const generator = login(user, {});

      expect(generator).toBe(SOME_VALUE_HERE));
  }));
});

For a detailed conversation about other workarounds and the track the feature in Jest, visit Generator support in Jest

like image 134
Farzad Yousefzadeh Avatar answered Nov 15 '22 03:11

Farzad Yousefzadeh