-
-
Notifications
You must be signed in to change notification settings - Fork 225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
mocking the print command without mocking the module #782
Comments
Hello. Interesting problem.
We absolutely do use react-to-print/src/utils/startPrint.ts Line 66 in 26a722f
What might be tripping you up here is that the I'm not a vitest expert, but if you can figure out how to get it to mock the |
I asked an LLM how to do this. Here is that conversation. Seems a bit hacky, but also like it might work? I have not tested this:
import { beforeAll, describe, it, expect, vi } from 'vitest';
// Mock for window.print
const mockPrint = vi.fn();
beforeAll(() => {
// Store the original createElement method
const originalCreateElement = document.createElement;
// Override the createElement method to intercept iframe creation
document.createElement = function (tagName) {
const element = originalCreateElement.call(document, tagName);
if (tagName.toLowerCase() === 'iframe') {
// Once the iframe is added to the document, override its print method
element.addEventListener('load', () => {
element.contentWindow.print = mockPrint;
});
}
return element;
};
});
describe('iframe tests', () => {
it('should mock print method on iframe', async () => {
// Your test code that creates an iframe
// ...
// After your iframe is created and loaded, you can assert that the mockPrint function was called
// Call the print method on the iframe to test
// iframe.contentWindow.print();
// Check if the mocked function was called
expect(mockPrint).toHaveBeenCalled();
});
});
// Remember to restore the original createElement method after your tests
afterAll(() => {
document.createElement = originalCreateElement;
}); |
I cannot use
vi.mock
in my browser based tests because it will override mymsw
network interceptors.Because of this, I cannot mock this module, leading to the print dialog popping up in my browser tests, causing my tests to hang. Locally, I can close the dialog, but in my CI pipelines, there is no way for me to close them, leading to never-ending tests.
In my test setup file, I have tried:
but (seemingly) because this repo does not directly use
window.print()
, it is not working as expected.react-to-print/src/utils/startPrint.ts
Line 66 in 26a722f
I would like to know if there is any recommended workaround to this that I can employ without modifying my source code?
Thank you.
Parent Issues: mswjs/msw#2398 , vitest-dev/vitest#6766 , vitest-dev/vitest#7290
The text was updated successfully, but these errors were encountered: