-1
Hello I have got a constant file set like this in an React project:
src/constants/env.ts
export default {
PROD: ['prod', 'production'].includes((process.env.NODE_ENV || '').toLowerCase())
}
This file is used to set some settings as in the example below:
src/utils/storage/Storage.ts
import ENV from 'src/constants/env'
class Storage {
async get<T = any>(key: string): Promise<T | undefined> {
return await new Promise((resolve) => {
try {
let value = localStorage.getItem(key) as string
if (value) {
if (ENV.PROD) value = btoa(value)
resolve(JSON.parse(value) as any as T)
}
} catch (error) { }
resolve(undefined)
})
}
async set(key: any, value: any): Promise<void> {
return await new Promise((resolve) => {
try {
value = JSON.stringify(value)
if (ENV.PROD) value = atob(value)
localStorage.setItem(key, value)
} catch (error) {
console.log(error.message)
}
resolve()
})
}
}
export default new Storage()
And I’m trying to mock the value of PROD
as true
for the Storage class to read ENV as true and then save the data to Base64.
src/utils/storage/Storage.test.ts
import Storage from './Storage'
import ENV from 'src/constants/env'
describe('Storage', () => {
const key = 'test'
const value = { test: 'test' }
const { PROD } = ENV
beforeEach(() => {
localStorage.clear()
ENV.PROD = false
})
afterAll(() => ENV.PROD = PROD)
describe('set', () => {
test('should set encoded base64 data if prod mode', async () => {
ENV.PROD = true
await Storage.set(key, value)
expect(localStorage.getItem(key)).toEqual(atob(JSON.stringify(value)))
})
})
})
But I’m not getting the Storage class to read the PROD value as true. What is required to mock this constants file? Can anyone help me?
Maybe I can help: Manual Mocks.
– Gustavo Sampaio
I saw no place in the documentation that allowed me to mock this constant file... some other idea
– LeandroLuk