3

我是 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调用了 store 的方法。

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

1)试图直接模拟商店的方法调度(例如doing jest.spyOn(store, 'dispatch')jest.mock('@/store'))。

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

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

正在做

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

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

谢谢您的回答。

4

0 回答 0