我需要测试一个在浏览器中打开一个新标签的函数
openStatementsReport(contactIds) {
window.open(`a_url_${contactIds}`);
}我想模拟窗口的open函数,这样我就可以验证传递给open函数的URL是否正确。
使用Jest,我不知道如何模拟window。我试图用一个模拟函数来设置window.open,但是这种方法不起作用。下面是测试用例
it('correct url is called', () => {
window.open = jest.fn();
statementService.openStatementsReport(111);
expect(window.open).toBeCalled();
});但是它给了我一个错误
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function anonymous]我应该对测试用例做什么?
发布于 2019-07-12 10:46:19
下面的方法对我有效。这种方法允许我测试一些在浏览器和Node.js中都可以工作的代码,因为它允许我将window设置为undefined。
这是Jest 24.8 (我相信):
let windowSpy;
beforeEach(() => {
windowSpy = jest.spyOn(window, "window", "get");
});
afterEach(() => {
windowSpy.mockRestore();
});
it('should return https://example.com', () => {
windowSpy.mockImplementation(() => ({
location: {
origin: "https://example.com"
}
}));
expect(window.location.origin).toEqual("https://example.com");
});
it('should be undefined.', () => {
windowSpy.mockImplementation(() => undefined);
expect(window).toBeUndefined();
});发布于 2017-01-27 15:19:39
使用global代替window
it('correct url is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});您也可以尝试
const open = jest.fn()
Object.defineProperty(window, 'open', open);发布于 2020-01-12 22:17:24
有几种方法可以在Jest中模拟全局变量:
mockImplementation方法(最类似Jest的方法),但它只适用于那些具有jsdom提供的一些默认实现的变量。window.open就是其中之一:test('it works',() => { // Setup const mockedOpen = jest.fn();//如果不制作副本,您将遇到循环依赖问题const originalWindow ={ ...window };const windowSpy = jest.spyOn(global," window ","get");windowSpy.mockImplementation(() => ({ ...originalWindow,//如果您需要其他窗口属性打开: mockedOpen }));//测试statementService.openStatementsReport(111) expect(mockedOpen).toBeCalled();//清理windowSpy.mockRestore();});
window变量的错误消息,例如window.href。test('it works',() => { // Setup const mockedOpen = jest.fn();const originalOpen = window.open;window.open = mockedOpen;//测试statementService.openStatementsReport(111) expect(mockedOpen).toBeCalled();// Cleanup window.open = originalOpen;});
与直接使用全局值相比,从另一个文件导入全局值可能更干净,因此使用Jest时模拟将变得微不足道。
文件./test.js
jest.mock('./fileWithGlobalValueExported.js');
import { windowOpen } from './fileWithGlobalValueExported.js';
import { statementService } from './testedFile.js';
// Tests
test('it works', () => {
statementService.openStatementsReport(111)
expect(windowOpen).toBeCalled();
});File./fileWithGlobalValueExported.js d.js
export const windowOpen = window.open;文件./testedFile.js
import { windowOpen } from './fileWithGlobalValueExported.js';
export const statementService = {
openStatementsReport(contactIds) {
windowOpen(`a_url_${contactIds}`);
}
}https://stackoverflow.com/questions/41885841
复制相似问题