我正在尝试对redux-saga进行测试。当我因某些未知原因而执行generator.next(data).value时,数据不会传递给saga函数,如下所示:
const gen = onCreateMessage()
const message = "aa"
gen.next(message).value
/// SAGA FUNCTION
export function* onCreateMessage(message) {
yield put(addMessage(message.payload))
错误讯息。无法读取未定义的有效负载。
答案 0 :(得分:1)
问题是你的生成器函数接受message
作为参数,所以你需要在初始化生成器时传递它:
const gen = onCreateMessage( /* the message */ )
然后您可以通过执行gen.next().value
并验证您的断言来获取下一个值。
这是一个带有示例的JS Bin:http://jsbin.com/catisu/edit?js,console
const { put, take } = ReduxSaga.effects;
const { expect } = chai;
const createMessage = message => ({
type: 'CREATE_MESSAGE',
payload: message,
});
const addMessage = message => ({
type: 'ADD_MESSAGE',
payload: message,
});
function* onCreateMessage(message) {
yield put(addMessage(message.payload));
}
// In your test
const message = 'some message';
// Message is passed when the generator is initialized
const gen = onCreateMessage(createMessage(message))
let next = gen.next();
// Using Chai here but with tape it'd be the same concept
try {
expect(next.value).to.eql(
put(addMessage(message))
);
console.log('It works!');
} catch(e) {
console.error('bummer');
}

<script src="https://npmcdn.com/redux-saga@0.11.1/dist/redux-saga.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
&#13;
也很小,但看起来你的生成器期望一个带有payload
键的对象,所以一个普通的字符串不会工作。