Last active
August 20, 2020 16:06
-
-
Save skimi/07a721316e9593d5cb248c1e54538c58 to your computer and use it in GitHub Desktop.
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
// These are extracted from a project using pollyJS in Cypress | |
// They might not work, I've just copy/pastied what I thought was relevant and removed lines of codes specific to the project | |
const pollyConnect = ( | |
win, | |
{ mocks, mode, pollyName }, | |
) => { | |
console.log( | |
`%cInit polly ${pollyName} for location ${win.location}`, | |
'background: gray; color: white; padding: 5px', | |
); | |
const pollyBrowserFetch = new Polly(pollyName, { | |
mode, | |
adapters: ['fetch'], | |
adapterOptions: { | |
fetch: { | |
context: win, | |
}, | |
}, | |
persister: 'rest', | |
logging: false, | |
recordIfMissing: false, | |
recordFailedRequests: true, | |
timing: Cypress.config('pollyTiming') || Timing.fixed(0), | |
matchRequestsBy: { | |
/* configure what matters in your requests */ | |
}, | |
}); | |
Cypress.config('pollyBrowserFetch', pollyBrowserFetch); | |
const { server } = pollyBrowserFetch; | |
if (mocks) { | |
server.host('my-host', () => { | |
mocks(pollyBrowserFetch); | |
}); | |
} | |
}; | |
Cypress.Commands.add( | |
'pollyVisit', | |
(url, { mocks, ...options } = {}) => { | |
const mode = Cypress.config('pollyMode') || 'replay'; | |
const pollyName = Cypress.config('pollyName'); | |
let pageLoadCount = 0; | |
cy.on('window:before:load', (win) => { | |
pageLoadCount++; | |
if (pageLoadCount === 1) { | |
pollyConnect(win, { mocks, mode, pollyName }); | |
return; | |
} | |
// If you want to support page reloads / changes you'll need to create new polly instances | |
pollyReconnect(win, { pageLoadCount, mode, pollyName }); | |
}); | |
return cy.visit(url, options); | |
}, | |
); | |
beforeEach(function () { | |
// In the beforeEach we generate a unique id/name for the test | |
// pollyJS will use that name to store its recordings | |
Cypress.config('pollyName', generateUniqueName(this.currentTest')); | |
}); | |
afterEach(() => { | |
// Commit mocks to disk | |
// polly.stop() is a promise and prevents the test from finishing while pollyJS still has requests in flight | |
cy.wrap(null, { log: false }).then(() => { | |
const pollyBrowserFetch = Cypress.config('pollyBrowserFetch'); | |
return pollyBrowserFetch.stop() | |
}); | |
}); | |
// In the test I set global pollymode to record or replay | |
Cypress.config('pollyMode', 'replay'); | |
// In the tests I use `pollyVisit` instead of `visit` | |
cy.pollyVisit('/my-page', { | |
mocks: ({server}) => server.post('/my-manually-mocked-route').intercept((req, res) => res.status(200).json({ mocked: 'mock' })) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment