LoginSignup
5
0

More than 1 year has passed since last update.

Cypressで別オリジンのページに遷移させる

Posted at

これはなに?

別オリジンのページ遷移ができなく、見積もり1日のタスクに2日を要してしまったので同じ轍を踏まないように記録として残しておきます。

この記事が同様の問題で悩んでいる人の助けになれば幸いです。

TL; DR

解決方法だけ先に記述しておきます。

cypress.jsonで以下を設定する

{
	"chromeWebSecurity": false,
}

課題

筆者の所属している会社では婚活サービスのWebリプレイスをしています。

リプレイスをするにも少し規模が大きいので段階的に移行をしているのですがその中で、以下の遷移ができるかの確認が必要な場面が発生しました。

リプレイス後のページ → リプレイス前のページ

移行リプレイス前後のページを以下のように表します

  • リプレイス後:ページA
  • リプレイス前:ページB

素直に実装すると以下のようになるのですが、結果はエラーになりました。

view_pageA.spec.ts
describe('ページAに関する表示確認', () => {
  beforeEach(() => {
    cy.visit('/pageA/')
  })

  it('ページBへ正常に遷移できる', () => {
    cy.get('.pageBLink').click()
    cy.location('pathname').should(path => {
      expect(path).to.eq('https://pageB.com')
    })
  })
})
エラー本文
    Cypress detected a cross origin error happened on page load:
    
      > Blocked a frame with origin "http://localhost" from accessing a cross-origin frame.
    
    Before the page load, you were bound to the origin policy:
    
      > http://localhost
    
    A cross origin error happens when your application navigates to a new URL which does not match the origin policy above.
    
    A new URL does not match the origin policy if the 'protocol', 'port' (if specified), and/or 'host' (unless of the same superdomain) are different.
    
    Cypress does not allow you to navigate to a different origin URL within a single test.
    
    You may need to restructure some of your test code to avoid this problem.
    
    Alternatively you can also disable Chrome Web Security in Chromium-based browsers which will turn off this restriction by setting { chromeWebSecurity: false } in cypress.json.[Learn more](https://on.cypress.io/cross-origin-violation)

解決方法

Cypress does not allow you to navigate to a different origin URL within a single test.

異なるorigin URLには遷移できないと書かれています。

Alternatively you can also disable Chrome Web Security in Chromium-based browsers which will turn off this restriction by setting { chromeWebSecurity: false } in cypress.json.Learn more

エラーにも書かれているようにcypress.jsonchromeWebSecurity: falseと設定することでこの問題を回避できました。

注意点

プロパティ名にもある通り、セキュリティ設定をオフにするので以下の箇所に影響が出るので注意してください。

  • セキュアでないコンテンツが表示される(Display insecure content)
  • クロスオリジンエラーの表示なしでスーパードメインへの遷移が可能になる(Navigate to any superdomain without cross-origin errors)
  • iframeへのアクセスが許容される(Access cross-origin iframes that are embedded in your application)

↓公式ドキュメントはこちら

余談

今回はこのエラーにたどりつく以前にDockerの知識が浅いので1日以上かかってしまいました。

ちょっとずつDockerの仕組みを理解して問題解決にかかる時間を短くしていきたいです。

ではまた!

参考記事

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0