如何在redux传奇生成器函数里面模拟变量?

问题描述 投票:0回答:1

如何测试下面的传奇?

export function* getSnapShotFromUserAuth(userAuth, additionalData) {
  try {
    const userRef = yield call(
      createUserProfileDocument,
      userAuth,
      additionalData
    );
    const userSnapshot = yield userRef.get();
    yield put(signInSuccess({ id: userSnapshot.id, ...userSnapshot.data() }));
  } catch (error) {
    yield put(signInFailure(error));
  }
}

我只能够让它工作到第一行。

describe("getSnapShotFromUserAuth", () => {
  const mockUserAuth = {};
  const mockAdditionalData = {};
  const generator = getSnapShotFromUserAuth(mockUserAuth, mockAdditionalData);

  it("should get snapshot from user auth", () => {
    expect(generator.next().value).toEqual(
      call(createUserProfileDocument, mockUserAuth, mockAdditionalData)
    );
  });
});

我怎么才能验证下一行?const userSnapshot = yield userRef.get();

我一直收到错误信息 TypeError: Cannot read property 'get' of undefined 当调用试图测试下一行时,因为它找不到 userRef. 有没有一种方法能够模拟下一行?

reactjs unit-testing testing react-redux redux-saga
1个回答
1
投票

你可以决定在调用的 yield 是由你传入的,当你调用 next(). 所以,比如说,在做完第一个 generator.next,你可以做。

const mockUserRef = {
  get: jest.fn();
}
expect(generator.next(mockUserRef).value).toEqual(/* whatever */);

0
投票

回答 -

it("should check for signInSuccess", () => {
    const myMock = jest.fn();
    let userRef = {
      get: myMock.mockReturnValue({
        id: 1,
        data: () => {},
      }),
    };

    let userSnapshot = {
      id: 1,
      data: () => {},
    };
    generator.next(userRef);

    expect(generator.next(userSnapshot).value).toEqual(
      put(signInSuccess({ id: userSnapshot.id, ...userSnapshot.data() }))
    );
  });
© www.soinside.com 2019 - 2024. All rights reserved.