我正在为一个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 是未定义的,它没有被注册,但我不太确定原因。感谢您的帮助。
ShopDispatcher = undefined
,这正是它应该做的。这是 coffeescript 的等价形式:var cat;
cat = "cat";
无论如何,在文件顶部明确地模拟调度程序jest.mock "../../app/scripts/dispatchers/shop_dispatcher.coffee"
导致测试通过。我相信要求 ShopDispatcher 是要求实际的 ShopDispatcher,而这个实际的 ShopDispatcher 没有属性 Shop.register.mock,这导致了测试失败。我将深入研究 jest 并编写更多测试。谢谢你的帮助! - johnnyutah