我想测试我的函数是否已正确触发(使用正确的参数),但是我找不到方法...
我有一个自定义的addEventListener,它使用媒体查询的名称,媒体查询本身和调度函数
// ... Inside my class
addEventListener(name, mediaQuery, dispatch) {
// Initialize the mediaQueryList and store it in our list
const mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addListener(
mediaQueryListEvent => this.onScreenChange(name, mediaQueryListEvent)
);
this.mediaQueries.set(name, {
mediaQueryList,
dispatch
});
// Then we look even for the first time on which breakPoint we are
this.searchAndDispatchBreakpoint(name, mediaQueryList);
}
有什么想法可以测试我的onScreenChange是否已使用正确的参数正确调用?
答案 0 :(得分:0)
好吧,经过数小时的搜索和尝试,我想出了一种方法。
我成功地模拟了window.matchMedia和里面的addListener 完成后,我只需要测试发送到我的方法的参数即可。
这是我的笑话
it('should test the media query addListener method', () => {
const bpManager = new BreakpointManager();
const mediaQuery = 'max-width: 1080px';
const name = 'name';
const mediaQueryListEvent = 'mediaQueryListEvent';
bpManager.onScreenChange = jest.fn();
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: e => e(mediaQueryListEvent),
removeListener: jest.fn(),
}));
bpManager.addEventListener(name, mediaQuery, dispatch);
expect(window.matchMedia).toHaveBeenCalledWith(mediaQuery);
expect(bpManager.onScreenChange).toBeCalledWith(name, mediaQueryListEvent);
});
还有我的方法addEventListener
addEventListener(name, mediaQuery, dispatch) {
// Initialize the mediaQueryList and store it in our list
const mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addListener(
mediaQueryListEvent => this.onScreenChange(name, mediaQueryListEvent)
);
this.mediaQueries.set(name, {
mediaQueryList,
dispatch
});
// Then we look even for the first time on which breakPoint we are
this.searchAndDispatchBreakpoint(name, mediaQueryList);
}