Created
August 29, 2021 22:10
-
-
Save sk39/dcdfd20ee0f916cf6b30af6e4fb85a67 to your computer and use it in GitHub Desktop.
Cypress用のMock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
cypress.json
Test Code