Write Unit Tests In Cypress With Mocking Node FS.readFileSync Method

Published: 14 January 2022
on channel: gleb bahmutov
1,711
17

If you have a lot of end-to-end Cypress tests and want to quickly add a few unit tests, you do not have to bring a second test runner. You can use Cypress to write and run unit tests, and even mock Node modules like fs.readFileSync if needed. Find the full source code for this example in repo https://github.com/bahmutov/cypress-t...

Example source code that uses fs.readFileSync

const fs = require('fs')
function findCasesInSpec(spec, readFile = fs.readFileSync) {
...
}
module.exports = { findCasesInSpec }

Example unit test that passes our stub to replace fs.readFileSync

import { findCasesInSpec } from '../../src/find-cases'

it('finds test case ids', function () {
const source = `
it('C101', ...)
`
const readFile = cy.stub().returns(source)
const ids = findCasesInSpec('spec1.js', readFile)
expect(ids).to.deep.equal([101])
expect(readFile).to.be.calledWith('spec1.js', 'utf8')
})


On this page of the site you can watch the video online Write Unit Tests In Cypress With Mocking Node FS.readFileSync Method with a duration of hours minute second in good quality, which was uploaded by the user gleb bahmutov 14 January 2022, share the link with friends and acquaintances, this video has already been watched 1,711 times on youtube and it was liked by 17 viewers. Enjoy your viewing!