如何模拟redux传奇生成器函数中的变量



如何测试下面的传奇?

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

相关内容

  • 没有找到相关文章

最新更新