We have an Angular project using the Monaco editor in the npm package ngx-monaco-editor-v2
version 17.0.1. We are running end-to-end tests using Cypress.
Using Cypress, I need a way to enter a block of text into the editor.
We currently have a method which I am not happy with:
cy.get("span[class='mtk1 bracket-highlighting-0']")
.eq(1)
.should('exist')
.type(`{selectall}{ctrl}{shift}K`, { delay: 100 })
cy.get('.view-line')
.should('have.text', '')
.type(cleanedJsonString, { delay: 0, release: false });
where cleanedJsonString
is the text to be entered into the editor.
This method is very slow, but it also screws up the formatting of the text.
Effectively, it enters line breaks, but never does a carriage return.
The text contains \n as a line break. I have tried replacing it with \r\n, but this didn't change the result.
Rather than typing the text, it might be more effective to paste the text into the editor. I don't know if this is possible, because writing to the clipboard from the browser is a security issue.
Does anyone know a good way to enter text into the Monaco editor using Cypress, in particular using the package ngx-monaco-editor-v2
in an angular project?
I received a quick answer to this question, which I marked as a solution.
Shortly afterwards the answer disappeared!
This is the solution that I am using, based on that answer.
// Patch the dashboard text into the monaco editor.
cy.window().then((win) => {
// First, check if monaco is available on the main window
const monacoInstance = (win as any).monaco || (win.frames[0] ? (win.frames[0] as any).monaco : null);
// If Monaco instance is found
if (monacoInstance) {
const editor = monacoInstance.editor.getModels()[0];
editor.setValue(dashboardText);
} else {
throw new Error('Monaco editor not found on the window or frames[0]');
}
});
Usually, the window
object contains a monaco
object.
So far as I know this is not documented.
Occasionally, I have found that it is not available on the window
object, but is available on frames[0]
. I have no explanation for that behavior.