當我試圖使用 Cypress 對 SAP 官網進行自動化操作時,遇到如下的錯誤訊息:
The following error originated from your application code, not from Cypress.
top.$ is not a function
When Cypress detects uncaught errors originating from your application it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by listening to the uncaught:exception event.
大意是,top.$ is not a function 這條錯誤訊息,是 SAP 官網 www.sap.com 報出來的,而非 Cypress 本身。對於此類情況,一種選擇是,我們可以在 Cypress 測試程式碼裡透過異常捕獲的方式,來忽略此類應用異常。
On a technical note, Cypress considers uncaught exceptions to be any error that is uncaught by your application, whether they are "standard" errors or unhandled promise rejections. If the error triggers the window's global error handler or its unhandledrejection handler, Cypress will detect it and fail the test.
需要強調的是,如果應用程式丟擲的異常,最終觸發了 windows 全域性錯誤處理器( global error handler ) 或者其 unhandledrejection handler,則 Cypress 同樣會監測到此情況,並且以失敗狀態終止其測試。
在 Cypress 裡禁掉應用程式錯誤訊息的完整程式碼:
/// <reference types="Cypress" />
describe('My First Test', () => {
it('finds the content "type"', () => {
cy.visit('https://www.sap.com');
cy.url().should('include', 'index.html');
/*
cy.contains('type').click();
cy.url().should('include', '/commands/actions');
cy.get('.action-email')
.type('jerry@email.com')
.should('have.value', 'jerry@email.com');
*/
});
});
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
console.log('Jerry errors!');
return false
})
最後的效果:
SAP 官網 web page 報出的錯誤訊息,並不會影響 Cypress 測試的繼續執行:
更多Jerry的原創文章,盡在:"汪子熙":