Skip to content

Commit

Permalink
add cache system
Browse files Browse the repository at this point in the history
  • Loading branch information
ruyadorno committed Dec 11, 2020
1 parent edee953 commit 3745cb2
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/mock.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
const Module = require('module')

const getKey = (a, b, c) =>
`${a}${b}${
JSON.stringify(c, (_, val) => typeof val !== 'object' ? String(val) : val)
}`

class Mock {
static cache () {
if (!this._cache)
this._cache = new Map()
return this._cache
}

static setToCache({ parentFilename, filename, mocks, module }) {
this.cache().set(getKey(parentFilename, filename, mocks), module)
}

static getFromCache({ parentFilename, filename, mocks }) {
return this.cache().get(getKey(parentFilename, filename, mocks))
}

constructor(parentFilename, filename, mocks = {}) {
this.filename = filename
this.mocks = new Map()
Expand All @@ -18,6 +37,12 @@ class Mock {
are the same used in ${filename} require calls`)
}

const cached = Mock.getFromCache({ parentFilename, filename, mocks })
if (cached) {
this.module = cached
return
}

const self = this
const callerTestRef = Module._cache[parentFilename]
const filePath = Module._resolveFilename(filename, callerTestRef)
Expand Down Expand Up @@ -48,6 +73,7 @@ are the same used in ${filename} require calls`)

this.module = new MockedModule(filePath, callerTestRef)
this.module.load(filePath)
Mock.setToCache({ parentFilename, filename, mocks, module: this.module })
}

static get(parentFilename, filename, mocks) {
Expand Down

0 comments on commit 3745cb2

Please sign in to comment.