React / Jest:如何测试store.dispatch

时间:2018-06-21 15:45:02

标签: redux jestjs redux-mock-store

我是Redux和Jest的新手,我正在努力解决问题。我要为此文件编写测试:

eventListeners.js

import store from '@/store';

chrome.runtime.onMessage.addListener((request) => {
  if (request.type === 'OAUTH_SESSION_RESTORED') {
    store.dispatch(completeLogin());
  }
});

我有这个文件:

eventListeners.test.js

 it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () => {
    // I have made a mock of `chrome.runtime.sendMessage` so the listener defined in eventListeners.js is called when doing that
    chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });

    // I want to test that store.dispatch got called
  });

但是,我未能成功测试商店的dispatch方法是否被调用。

到目前为止,我已经尝试过:

1)尝试直接模拟商店的方法分派(例如,进行jest.spyOn(store, 'dispatch')jest.mock('@/store'))。

但是似乎没有任何效果。我认为这是因为eventListeners.js中使用的商店不是规范中的商店。因此,嘲笑它不会做任何事情

2)使用https://redux.js.org/recipes/writing-tests中所述的redux-mock-store库。

const store = mockStore({})
chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
expect(store.getActions()).toEqual([{ type: 'LOGIN_COMPLETE' }])

但是,同样的问题(我想):规范中使用的商店与eventListeners.js中的商店不同。 store.getActions()返回[]

是否有一种很好的方法来测试store.dispatch被呼叫?

==================================

现在,我要做的是我订阅了商店,然后尝试查看商店是否已更改。如https://github.com/reduxjs/redux/issues/546

中所述
it('dispatches completeLogin when OAUTH_SESSION_RESTORED received', () => {
    const storeChangedCallback = jest.fn()
    store.subscribe(storeChangedCallback)
    chrome.runtime.sendMessage({ type: 'OAUTH_SESSION_RESTORED' });
    expect(storeChangedCallback).toHaveBeenCalled();
    })

有更好的方法吗?我错过了什么吗?

谢谢您的回答。

0 个答案:

没有答案