Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use getContext in testSaga unit test #384

Open
sbitproz opened this issue Apr 5, 2022 · 2 comments
Open

How to use getContext in testSaga unit test #384

sbitproz opened this issue Apr 5, 2022 · 2 comments

Comments

@sbitproz
Copy link

sbitproz commented Apr 5, 2022

Context

In the application we adopted Sagas to manage our side effects. We've tried to use this excellent library to improve our test readability of our tests and that the ordering of the yields are correct.

Our application provides our apis through the application using the Context API. This is where we've hit a slight speed bump in the test with getContext.

In our Sagas we're accessing the api through getContext from the redux-saga/effects package. e.g.

export function* aSaveGeneratorFunction(someAction) {
  ...
  const { payload: { someEntity } } = someAction
  const entityApi = yield getContext("entity")
  ....
 const responseFromApi = yield call([entityApi, `saveSomeEntity`], someEntity)
  ...
}

In our tests we're trying to mock this dependency


  it('should invoke effects in the right order', () => {
    const payload = { id: "id" }
    const action = { type: "entity/saveEntityRequest", payload }

    const saveSomeEntity = () => {
      return Promise.resolve([]);
    }

    getContext.mockImplementation((key: string) => ({
      entity: { saveSomeEntity }
    }))

    return testSaga(aSaveGeneratorFunction, action)
      ...
      .next()
      .getContext('entity')
      .next()
      ...
      .isDone();
  })

Our generator function fails to execute the mock function provided through the getContext.

  1. Are we using getContext in the correct way?
  2. Is there a particular way to mock getContext when using testSaga? (current this mocking works in expectSaga)
  3. Do you have any recommendations of how to approach this test?
@jp928
Copy link
Collaborator

jp928 commented Apr 7, 2022

@sbitproz Thanks for using this library.
Unfortunately, testSaga doesn't support mock getContext, but feel free to try use jest.mock() instead.
The way to test getContext is using expectSaga, see this PR: https://github.com/jfairbank/redux-saga-test-plan/pull/179/files

Also, feel free to propose your opinion to improve this.

@sbitproz
Copy link
Author

sbitproz commented Apr 7, 2022

Hi @jp928

Thanks for the efficient reply. Is it worth adding a detail about this on the documentation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants