javascript - 通过 Jest 测试,手动将值传递给生成器会产生意想不到的结果

标签 javascript reactjs generator jestjs

我有以下 redux saga,它进行 api 调用并处理结果:

import { takeLatest } from 'redux-saga'
import { call, put } from 'redux-saga/effects'
import { normalize, arrayOf } from 'normalizr'
import * as actions from './actions'
import * as schemas from './schemas'
import * as types from './actionTypes'
import { api, constants as apiConstants } from '../../services/api'

export function* fetchWorks() {
  const { response, error } = yield call(api.getJson, apiConstants.WORKS_ENDPOINT)
  if (response) {
    const normalized = normalize(response.items, arrayOf(schemas.works))
    yield put(actions.fetchWorksSuccess(normalized))
  } else {
    yield put(actions.fetchWorksFail(error))
  }
}

我正在测试这些 Jest 测试是否一切正常:

import { takeLatest } from 'redux-saga'
import { call, put } from 'redux-saga/effects'
import * as sagas from './sagas'
import * as actions from './actions'
import * as types from './actionTypes'
import { api, constants as apiConstants } from '../../services/api'

describe('works saga', () => {
  describe('fetchWorks', () => {
    it('should fetch data', () => {
      const generator = sagas.fetchWorks()
      const actual = generator.next().value
      const expected = call(api.getJson, apiConstants.WORKS_ENDPOINT)
      expect(actual).toEqual(expected)
    })

    // this test requires me to pass a response object to the generator
    it('should put fetchWorksSuccess on a response', () => {
      // so I create it here
      const response = {
        items: [{
          sys: { id: '1' },
          fields: { content: 'content' }
        }]
      }
      const generator = sagas.fetchWorks()
      const expected = put(actions.fetchWorksSuccess())
      // but I would expect to pass it here    
      generator.next()
      // but actually the test only succeeds if I pass it here
      const actual = generator.next({ response }).value
      expect(actual).toEqual(expected)
    })

    // same goes for this test
    it('should put fetchWorksFail on errors', () => {
      const error = new Error('Something went wrong')
      const generator = sagas.fetchWorks()
      const expected = put(actions.fetchWorksFail())
      generator.next()
      const actual = generator.next({ error }).value
      expect(actual).toEqual(expected)
    })
  })
})

但是,对于“应该在响应上放置 fetchWorksSuccess”“应该在错误上放置 fetchWorksFail” 测试,我必须手动传递 {response }{error} 对象分别放入每个生成器中。

我知道这些对象是必要的(因为 if 语句检查是否有响应),但我不明白为什么我必须将其传递给第二个 .next() 而不是第一个?因为在我看来,第一个 yield 产生响应或错误对象,而不是第二个。有谁明白为什么吗?

最佳答案

这不是 React 的东西,而是生成器的东西。

第一次调用generator.next()启动生成器,而不是从yield调用返回:

>>> function *example_generator() {
  console.log('before first yield', Array.slice(arguments));
  var first_yield = yield 'first';
  console.log('first yield returned', first_yield);
  var second_yield = yield 'second';
  console.log('second yield returned', second_yield);
  return 'done';
}
>>> generator = example_generator("generator", "creation")
Generator {}
>>> generator.next("first next")
before first yield  Array [ "generator", "creation" ]
Object { value: "first", done: false }
>>> generator.next("second next")
first yield returned second next
Object { value: "second", done: false }
>>> generator.next("third next")
second yield returned third next
Object { value: "done", done: true }

您对 fetchWorks() 的初始调用创建了生成器对象,但实际上并未启动生成器。

这样想 - 第一次调用 next() 会为您提供传递给第一个 yield 的值;第二次调用 next() 时给出的参数可让您指定第一个 yield 的返回值。

关于javascript - 通过 Jest 测试,手动将值传递给生成器会产生意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41314373/

相关文章:

javascript - 从外部 js 文件触发 js 事件,如 onclick

javascript - Redux-persist react native AsyncStorage 对象序列化对象不相等

javascript - 如何将 IntersectionObserver 与 React 结合使用?

python - python中的随机素数

javascript - Codecademy flipboard 代码无法在我的电脑上运行

javascript - 这个javascript代码是什么意思?

javascript - 测试等于条件时使用下划线时的奇怪行为

javascript - React-testing-library 渲染函数有什么问题?它对某些对象返回错误

c++ - 为什么具有默认分配参数的函数不被接受为 0-arg 生成器?

python - 从生成器函数中检索所有迭代器值