如何在 redux saga 生成器函数中模拟变量?

How to mock variables inside redux saga generator functions?

我如何测试下面的 saga?

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。有没有办法模拟下一行?

您可以通过调用 next() 时传入的内容来决定 yield 的结果。因此,例如,在完成第一个 generator.next 之后,您可以执行:

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

回答-

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() }))
    );
  });