How to mock not installed npm package in jest?
I'm writing a library and I need to test some cases when optional dependencies are not installed.
Update
My library has an optional dependency. The end-user of my library can optionally to install styled-components
.
In my tests (jest) I covered the case when styled-components
is installed.
Now I need to cover the case when the package is not installed.
test(`When styled-components is not installed`, () => {
process.env.SC_NOT_INSTALLED = true
const fn = () => {
const styled = require(`./styled`)
}
expect(fn).toThrow(Error)
})
let styled
try {
require.resolve(`styled-components`)
styled = require(`styled-components`)
if (process.env.NODE_ENV === `test` && process.env.SC_NOT_INSTALLED) {
throw new Error(`Imitation styled-components is not installed`)
}
}
catch {
styled = () => {
throw new Error(`Module not found: styled-components`)
}
}
export default styled
process.env.SC_NOT_INSTALLED
-> will not work because as I guess the test are running in different process.