madox2
madox2

Reputation: 51881

How to test functional selectors in redux saga?

Currently it is possible to write reducers and test sagas like this:

// selector
const selectThingById = (state, id) => state.things[id]

// in saga
const thing = yield select(selectThingById, id)

// and test
expect(gen.next().value)
  .toEqual(select(selectThingById, id))

However I want to use more functional approach to write my reducers and put data (state) last in arguments:

// selector
const selectThingById = R.curry((id, state) => state.things[id])

// in saga
const thing = yield select(selectThingById(id))

// test: this actually fails
expect(gen.next().value)
  .toEqual(select(selectThingById(id)))

The test fails because selectThingById(id) creates new function everytime.

This could be solved by option to prepend arguments to select instead of apending. Is it possible or is there any way how to test such selectors?

Upvotes: 1

Views: 1562

Answers (2)

Anastasia Sterh
Anastasia Sterh

Reputation: 1

Just export your function for importing in your test and put it to next:

// selector
export const selectThingById = R.curry((id, state) => state.things[id])

// in saga
const thing = yield select(selectThingById(id))

// test
expect(gen.next(selectThingById).value)
  .toEqual(select(selectThingById(id)))

Upvotes: 0

Martin Kadlec
Martin Kadlec

Reputation: 4975

You need to call the selector factory using the call effect so you can inject the right function to the saga using gen.next(val)

// in saga
const selector = yield call(selectThingById, id)
const thing = yield select(selector)

// test
const selector = selectThingById(id)
gen.next(selector)
  .toEqual(call(selectThingById, id))
expect(gen.next().value)
  .toEqual(select(selector))

Upvotes: 2

Related Questions