Jest单元测试中,Dispatcher未注册回调函数。

4

我正在为一个React+Flux应用程序中的存储编写单元测试。 我遵循了这里设置模拟调度程序的示例,我的单元测试如下:

jest.dontMock "../../app/scripts/stores/item_store.coffee"
jest.dontMock "object-assign"

describe 'ItemStore', ->
  ShopConstants = require "../../app/scripts/constants/shop_constants.coffee"
  ShopDispatcher = undefined
  ItemStore = undefined
  callback = undefined

  actionBuildQueryString =
    source: "VIEW_ACTION"
    action:
      type: ShopConstants.ActionTypes.BUILD_QUERY_STRING
      size: "4"

  actionReceiveFilterRespData =
    source: "SERVER_ACTION"
    action:
      type: ShopConstants.ActionTypes.RECEIVE_FILTER_RESP_DATA
      data: {item: {} }

  beforeEach ->
    ShopConstants = require "../../app/scripts/constants/shop_constants.coffee"
    ShopDispatcher = require "../../app/scripts/dispatchers/shop_dispatcher.coffee"
    ItemStore = require "../../app/scripts/stores/item_store.coffee"
    callback = ShopDispatcher.register.mock.calls[0][0]

  it "registers a callback with the dispatcher", ->
    expect(ShopDispatcher.register.mock.calls.length).toBe(1)

在我的item_store.coffee文件中,我向调度程序注册如下:
ShopDispatcher.register (payload) ->
  action = payload.action

  switch action.type

    when ActionTypes.BUILD_QUERY_STRING
      WebApiUtils.fetchItems(payload)

    when ActionTypes.RECEIVE_FILTER_RESP_DATA
      _setItems(action.data)

  ItemStore.emitChange()

我希望模拟的 Dispatcher 能够注册回调函数,因为在实际的 item_store 文件中会发生这种情况,而我已经告诉 jest 不要模拟它。然而,由于 ShopDispatcher.register 是未定义的,它没有被注册,但我不太确定原因。感谢您的帮助。


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - fisherwebdev
它正在覆盖开头的 ShopDispatcher = undefined,这正是它应该做的。这是 coffeescript 的等价形式: var cat; cat = "cat"; 无论如何,在文件顶部明确地模拟调度程序jest.mock "../../app/scripts/dispatchers/shop_dispatcher.coffee" 导致测试通过。我相信要求 ShopDispatcher 是要求实际的 ShopDispatcher,而这个实际的 ShopDispatcher 没有属性 Shop.register.mock,这导致了测试失败。我将深入研究 jest 并编写更多测试。谢谢你的帮助! - johnnyutah
1个回答

0

我之前也遇到了同样的问题。不要使用 ShopDispatcher.register.mock.calls[0][0],而是尝试使用 ShopDispatcher.dispatch。下面这段代码对我来说完美地工作了(使用 TypeScript)。

beforeEach(function () {   
    dispatcher = require("../../../src/App/Dispatcher");
    localeStore = require("../../../src/stores/localestore");
    localeAction = require("../../../src/actions/Locale/LocaleAction");
}

it("should translate the element with the value in current locale JSON", function () {
   localeChangeAction = new localeAction(true, locale, localeJson);
   dispatcher.dispatch(localeChangeAction);

   var translatedText = localeStore.instance.TranslateText("login.login-header");
        expect(translatedText).toEqual("Login header");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接