与玩笑反应undux测试(模拟)

时间:2020-07-02 10:39:00

标签: reactjs jestjs

请我如何测试 .subscribe 作为 .on 上的链接功能:

在组件中:

store.on('event').subscribe(val => {
    ...
});

测试:

const mockStore = {
    get: () => null,
    set: () => {},
    on: () => jest.fn(),
};

describe('TEST', () => {
    const wrapper = shallow(<component store={mockStore} />);
    
    it('Should render', () => {
          expect(wrapper.exists()).toBe(true);
    });
});

获取并设置作品,

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

我还没有测试过,但是我认为以下应该可以工作:

您可以返回一个包含on函数的对象,而不用jest.fn()模拟subscribe函数。像这样:

const mockStore = {
    get: () => null,
    set: () => {},
    on: (eventStr) => ({
        subscribe: jest.fn(),
    }),
};
const subscribeSpy = jest.spyOn(mockStore.on('event'), 'subscribe');

然后期望在需要时调用它,

expect(subscribeSpy).toHaveBeenCalled();