Skip to content

Commit

Permalink
test(plugin): add some utils for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
mohatt committed Feb 15, 2021
1 parent f846684 commit 659a3ab
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"parse5": "^6.0.0",
"parse5-htmlparser2-tree-adapter": "^6.0.0",
"purgecss": "^4.0.0",
"filesize": "^6.1.0"
"filesize": "^6.1.0",
"mkdirp": "^1.0.4"
},
"devDependencies": {
"@babel/cli": "7.12.16",
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions test/__mocks__/fs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import MemoryFS from 'metro-memory-fs'
// Make sure we export this as a cjs module
module.exports = new MemoryFS({
cwd: () => '/virtual/project'
})
70 changes: 70 additions & 0 deletions test/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import fs from 'fs'
import path from 'path'
import mkdirp from 'mkdirp'
import { onPreBootstrap } from '../src'

/**
* Make sure to mock the fs module in your test
* file before using any of these functions
*/

/**
* Virtual project root directory
* @see /test/__mocks__/fs.js
* @type {string}
*/
export const programRoot = '/virtual/project'

/**
* Changes plugin options by invoking the onPreBootstrap hook
* Tests that run after calling this function will receive
* the mounted options
*
* Note: Make sure to wrap this in a try..catch block when you
* pass custom options since it may throw errors
*
* @param {Object} options
*/
export function mountOptions (options = {}) {
onPreBootstrap({
store: {
getState: () => ({
program: { directory: programRoot }
})
},
reporter: {},
pathPrefix: ''
}, options)
}

/**
* Mounts a directory on the virtual filesystem
*
* @param {string} dirname
*/
export function mountDir (dirname) {
dirname = path.resolve(programRoot, dirname)
!fs.existsSync(dirname) ? mkdirp.sync(dirname) : null
}

/**
* Mounts a file on the virtual filesystem
*
* @param {string} filename
* @param {string} content
*/
export function mountFile (filename, content = '//noop') {
mountDir(path.dirname(filename))
fs.writeFileSync(path.resolve(programRoot, filename), content.toString())
}

/**
* Mocks a virtual module by path Usefull when requiring
* a module that doesn't exist on the filesystem
*
* @param {string} name - module name
* @param {object} exports - module exports
*/
export function mountModule (name, exports) {
jest.doMock(path.resolve(programRoot, name), () => exports, { virtual: true })
}

0 comments on commit 659a3ab

Please sign in to comment.