Skip to content

Instantly share code, notes, and snippets.

@sk39
Created August 29, 2021 22:10
Show Gist options
  • Save sk39/dcdfd20ee0f916cf6b30af6e4fb85a67 to your computer and use it in GitHub Desktop.
Save sk39/dcdfd20ee0f916cf6b30af6e4fb85a67 to your computer and use it in GitHub Desktop.
Cypress用のMock
import { getTestTitle } from './utils'
const mockDataPath = './cypress/fixtures/mocks'
export default function useMock(mockMode?: string) {
let mockData = []
const mode = mockMode || Cypress.env('mockMode')
const isRecord = mode === 'record',
isReplay = mode === 'replay'
const apiUrls = Cypress.env('mockApiUrls')
beforeEach(() => {
if (isRecord) {
apiUrls.forEach((api) => {
cy.intercept(`${api.url}/**`, (req) => {
// interceptを有効にすると一部のAPI(/tagsで発生)のbodyがEmptyとなる(内部的にはArrayBufferとなる)
// 関連あるかも → https://github.com/cypress-io/cypress/issues/16292
// 発生条件等よくわからんが、ArrayBufferの場合は変換する処理をいれる
req.continue((res) => {
const { body } = res
if (body.byteLength) {
console.log('[Patch] Correct for ArrayBuffer', req.url, body)
res.body = new TextDecoder().decode(body)
}
})
req.on('response', (res) => {
const { url, method } = req
const { body, headers, statusCode } = res
const sameEndpoint = mockData.find(
(d) => d.url === url && d.method === method
)
if (sameEndpoint) return
mockData.push({ url, method, res: { body, headers, statusCode } })
})
})
})
}
})
beforeEach(() => {
if (isReplay) {
const path = `${mockDataPath}/${getTestTitle()}.json`
cy.readFile(path).then((recordData) => {
cy.log(`Load MockData length=${recordData.length}`)
recordData.forEach((record) => {
let { method, url, res } = record
apiUrls.some((api) => {
if (!api.alias || !url.includes(api.alias)) return false
url = url.replace(api.alias, api.url)
return true
})
cy.intercept(method, url, res)
})
})
}
})
afterEach(() => {
if (isRecord) {
const path = `${mockDataPath}/${getTestTitle()}.json`
cy.writeFile(path, mockData).then(() => {
cy.log(`Save MockData length=${mockData.length}`)
mockData = []
})
}
})
return cy
}
@sk39
Copy link
Author

sk39 commented Aug 29, 2021

Usage

cypress.json

{
  "env": {
    "mockMode": "passthrough",
    "mockApiUrls": [
      {
        "url": "http://localhost:5000",
        "alias": "https://xxx.xxx"
      },
      {
        "url": "http://localhost:5001",
        "alias": "https://xxx.xxx"
      }
    ]
  }
}

Test Code

context('hoge-screen', () => {
  useMock()

  it('Hoge Test', () => {
    ...
  })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment