我正在尝试对使用redux-saga的react应用程序进行单元测试。 以下是我的传奇文件:
// sagas.js
export function* getDataFromServer() {
try {
const foo = yield select(fooSelector());
const bar = yield call(barRequest);
yield put(actions.SOME_ACTION.request());
const mainResponse = yield call(
api.getData,
bar,
foo.some_number,
foo.some_other_number,
);
} catch () {
throw error;
}
}
下面是我的单元测试用例:
// sagas.test.js
describe("getDataFromServer", () => {
const generator = getDataFromServer();
it("should get Data", () => {
expect(generator.next().value).toEqual(select(fooSelector()));
expect(generator.next().value).toEqual(call(barRequest));
expect(generator.next().value).
toEqual(put(actions.SOME_ACTION.request()));
expect(generator.next().value).toEqual(
call(
api.getData,
bar,
foo.some_number,
foo.some_other_number,
)
);
});
});
但是最后一次给我的错误是“无法读取未定义的属性“ some_number”。这很明显,因为开玩笑实际上并没有在saga单元测试中运行所有效果。但是我想知道有什么办法我可以在上一条语句中传递多个yield的值吗?
expect(generator.next(foo, bar).value).toEqual(
call(
api.getData,
bar,
foo.some_number,
foo.some_other_number,
)
);
答案 0 :(得分:0)
这是回答我问题的article。
我做了这样的事情:
// sagas.test.js
const foo = {
some_number = "some_number",
some_other_number = "some_other_number"
};
const bar = "bar";
describe("getDataFromServer", () => {
const generator = getDataFromServer();
it("should get Data", () => {
expect(generator.next().value).toEqual(select(fooSelector()));
expect(generator.next(foo).value).toEqual(call(barRequest));
expect(generator.next(bar).value).
toEqual(put(actions.SOME_ACTION.request()));
expect(generator.next().value).toEqual(
call(
api.getData,
bar,
foo.some_number,
foo.some_other_number,
)
);
});
});