玩笑的Redux Saga单元测试:如何维持参加测试的对象?

时间:2018-07-08 11:01:08

标签: unit-testing redux jestjs redux-saga redux-saga-test-plan

我是单元测试,Redux和Redux Saga的新手。我将它与React Native一起使用。我只是像docs of Redux Saga中所述的那样实现了loginFlow

function* loginFlow() {
  while (true) {
    const {user, password} = yield take('LOGIN_REQUEST')
    // fork return a Task object
    const task = yield fork(authorize, user, password)
    const action = yield take(['LOGOUT', 'LOGIN_ERROR'])
    if (action.type === 'LOGOUT')
      yield cancel(task)
    yield call(Api.clearItem, 'token')
  }
}

function* authorize(user, password) {
  try {
    const token = yield call(Api.authorize, user, password)
    yield put({type: 'LOGIN_SUCCESS', token})
    yield call(Api.storeItem, {token})
    return token
  } catch(error) {
    yield put({type: 'LOGIN_ERROR', error})
  } finally {
    if (yield cancelled()) {
      // ... put special cancellation handling code here
    }
  }
}

我现在正在尝试为此Auth流编写测试。不幸的是,我无法弄清楚如何为*loginFlow生成器进行测试,电子邮件和密码。这是我目前所在的位置:

describe("login flow", () => {
  const gen = loginFlow();
  const user = "test@test.test";
  const password = "testpassword";

  it("should wait for a user to log in", () => {
    expect(gen.next({ user, password }).value).toEqual(take(LOGIN_REQUEST));
  });

  it("should fork the handling of the login request", () => {
    const expectedYield = fork(authorize, user, password);
    expect(gen.next().value).toEqual(expectedYield);
  });
});

问题是,这引发了错误:

● login flow › should fork the handling of the login request

    TypeError: Cannot read property 'email' of undefined

      28 | export function* loginFlow() {
      29 |   while (true) {
    > 30 |     const { email, password } = yield take(LOGIN_REQUEST);

         |             ^
      31 |     // fork return a task object
      32 |     const task = yield fork(authorize, email, password);
      33 |     const action = yield take([LOGOUT, LOGIN_ERROR]);

如您所见,我试图通过在下一个调用中提供它们来将这些值提供给yield关键字,但这只是行不通。

1 个答案:

答案 0 :(得分:0)

尝试了很多之后,我才发现它。

这是我必须更改测试的方式:

describe("login flow", () => {
  const gen = loginFlow();
  const email = "test@test.test";
  const password = "testpassword";

  it("should wait for a user to log in", () => {
    expect(gen.next().value).toEqual(take(LOGIN_REQUEST));
  });

  it("should fork the handling of the login request", () => {
    const expectedYield = fork(handleLoginRequest, email, password);
    expect(gen.next({ email, password }).value).toEqual(expectedYield);
  });
});