Stub the browser FileSystem API
Bonus day 28: stub the file system access from the test
If your application is using the browser FileSystem APIs the tests can stub those window methods to return mock data. For example, the following application from the repo bahmutov/cypress-browser-file-system-example shows the contents of the file selected by the user:
let fileHandle
// Destructure the one-element array.
;[fileHandle] = await window.showOpenFilePicker()
const file = await fileHandle.getFile()
const contents = await file.text()
document.getElementById('output').textContent = contentsFrom the Cypress test, stub the method itself and return mock objects all the way down to file.text method:
cy.visit('/', {
onBeforeLoad(win) {
const file = {
text: cy.stub().resolves('Hello, world!'),
}
const fileHandle = {
getFile: cy.stub().resolves(file),
}
cy.stub(win, 'showOpenFilePicker')
.resolves([fileHandle])
},
})Once the method is stubbed, we can check the user interface
cy.get('button').click()
cy.get('#output').should('have.text', 'Hello, world!')
cy.get('@text').should('be.called')The test gives us confidence in our code
For the full discussion, read the new blog post “Test Web Apps That Use The Browser FileSystem API”


