开玩笑:window.print 未实施

jest: window.print not implemented

我开玩笑做的每件事,错误都不会修复并继续显示在下面:

 console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.alert
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at util_ajvSchemaValidator (D:\Docs\Projects\EMM\emm_next\src\utils\commonUtility.ts:1557:5)
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:78:30)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:56:12
        at new Promise (<anonymous>)
        at mapper (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:43:19)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\queue_runner.js:87:41
        at processTicksAndRejections (internal/process/task_queues.js:94:5) undefined

  console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Not implemented: window.print
        at module.exports (D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
        at D:\Docs\Projects\EMM\emm_next\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\browser\Window.js:594:7
        at Object.<anonymous> (D:\Docs\Projects\EMM\emm_next\tests\unit\utils\commonUtility.test.ts:127:5)
        at Object.asyncJestTest (D:\Docs\Projects\EMM\emm_next\node_modules\jest-jasmine2\build\jasmine_async.js:108:37)
 FAIL  tests/unit/utils/commonUtility.test.ts (6.407s)jest-jasmine2\build\queue_runner.js:56:12
  util_sum

我什至使用了 npm i jsdom,但它并没有解决问题。甚至添加 "testEnvironment":"jsdom" 至 package.json,但问题并未解决。 有什么正确的方法可以解决这个问题吗?

我遇到了同样的问题,我是这样解决的:

在测试每个使用 window.print 的组件时,我添加了这个:

describe('Test.spec.js', () => {
    let jsdomPrint;

    beforeEach(() => {
        jsdomPrint = window.print;
        jest.spyOn(window, 'print').mockImplementation(() => {});
    });

    ...

    afterEach(() => {
        window.print = jsdomPrint;
    });
});

自 window.alert 起,需要手动消除打印和其他几个特定于浏览器的副作用。这最好用 Jest 来完成,这样间谍就可以被跟踪和清理:

jest.spyOn(window, 'alert').mockReturnValue();
jest.spyOn(window, 'print').mockReturnValue();
function printTheWebPage(){
  window.print();
}
describe("print", () => {
  it('should print', function () {
    printTheWebPage();
    expect(window.print).toHaveBeenCalled();
  });
});

有关详细信息,请参阅以下链接:

https://jestjs.io/docs/en/mock-function-api#mockfnmockreturnvaluevalue

https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom