tommyd456
tommyd456

Reputation: 10673

How do I test a saga with params

Learning how to test a saga (using Jest) for the first time. My saga requires an object passing to it containing a userId but I'm getting this error which is obviously highlighting a difference in the arguments:

Expected value to equal:
  {"@@redux-saga/IO": true, "CALL": {"args": [], "context": null, "fn": [Function getClassrooms]}}
Received:
  {"@@redux-saga/IO": true, "CALL": {"args": ["1"], "context": null, "fn": [Function getClassrooms]}}

I have:

import { call, put } from 'redux-saga/effects';

import { theSaga } from './saga.js';
import { apiCall } from './api';

it('should do something', () => {
  const data = {
    payload: {
      userId: '1'
    }
  };

  const generator = theSaga(data);

  expect(generator.next().value)
    .toEqual(call(apiCall));

});

Not sure how I would get the two to match? I've tried changing the line to:

.toEqual(call(apiCall('1'));

but this gives errors about the function not being a promise.

Upvotes: 1

Views: 1340

Answers (1)

Dennie de Lange
Dennie de Lange

Reputation: 2934

call is a saga function which returns an action to be executed by the saga middleware. call expects the arguments to the function to be appended to it's arguments, so call(apiCall,1). The nice thing about this is that the generator can be tested by simply walking each step and check if the expected action is generated. expect(generator.next().value).toEqual(call(apiCall,1))

That said; I don't see much use in testing a generator this way. You want to test behaviour instead of how the generator is implemented. You put something in and expect something out (under different circumstances). Testing something like expect(generator.next().value).toEqual(call(apiCall,1)) is like saying: I actually programmed what I've programmed, the test confirms that.

Upvotes: 1

Related Questions