redux-saga单元测试意外失败

时间:2017-09-22 11:26:27

标签: unit-testing redux-saga

我们有这样的功能:

export function* postPermitApplicationRequest() {
  try {
    const uris = yield select(state => getUris(state));

    .... (more yields hereafter)

我们用Jest和Chai测试这个函数如下:

...
const action = { type: Action.POST_PERMIT_APPLICATION };
const generator = postPermitApplicationRequest(action);    

it('must select uris from state', () => {
  const nextCall = generator.next().value;
  const uris = select(state => getUris(state));
  expect(nextCall).to.deep.equal(uris);
});

然而期望失败:

AssertionError: expected { Object (@@redux-saga/IO, SELECT) } to deeply equal { Object (@@redux-saga/IO, SELECT) }

  at Assertion.assertEqual (node_modules/chai/lib/chai/core/assertions.js:485:19)
  at Assertion.ctx.(anonymous function) [as equal] (node_modules/chai/lib/chai/utils/addMethod.js:41:25)
  at Object.<anonymous> (src/app/pa/PermitApplicationServiceSagas.test.js:20:43)
  at process._tickCallback (internal/process/next_tick.js:109:7)

这两个对象看起来都像:

{ '@@redux-saga/IO': true,
  SELECT: { selector: [Function], args: [] } }

然而选择器功能不同。 generator.next()的结果包含代码覆盖率跳过提示:

function (state) {/* istanbul ignore next */cov_zrpq42gyn.f[12]++;cov_zrpq42gyn.s[19]++;return (/* istanbul ignore next */(0, _Selectors.getUris)(state));}

虽然原始功能没有:

function (state) {return (0, _Selectors.getUris)(state);}

看起来generator.next()添加了这些提示,断言失败

我们错在哪里?

我们使用redux-saga 0.14.8

1 个答案:

答案 0 :(得分:2)

测试失败,因为在你的saga和测试中,每次执行代码时都会创建一个新函数。这两个函数将进行比较,但不是同一个实例。

你可以在你的传奇和测试中使用select(getUris),因为两者都会引用同一个函数。

你的传奇:

export function* postPermitApplicationRequest() {
  try {
    const uris = yield select(getUris);

    .... (more yields hereafter)

你的考试:

...
const action = { type: Action.POST_PERMIT_APPLICATION };
const generator = postPermitApplicationRequest(action);    

it('must select uris from state', () => {
  const nextCall = generator.next().value;
  const uris = select(getUris);
  expect(nextCall).to.deep.equal(uris);
});