调度程序未在开玩笑单元测试中注册回调

Dispatcher not registering callbacks in jest unit tests

本文关键字:注册 回调 单元测试 开玩笑 调度程序      更新时间:2023-09-26

我正在为 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()

我希望被模拟的调度程序注册回调,因为这发生在实际的item_store文件中,我已经告诉开玩笑不要嘲笑。 但是,由于ShopDispatcher.register未定义,因此没有注册,但我不太确定为什么。 任何帮助,不胜感激。

我也面临着同样的问题。与其使用ShopDispatcher.register.mock.calls[0][0]不如尝试ShopDispatcher.dispatch。下面的代码非常适合我(使用类型脚本)。

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");
});