feat: init serverless function

This commit is contained in:
Innei
2022-03-07 23:02:05 +08:00
committed by
parent eee7678300
commit b701428b02
5 changed files with 128 additions and 6 deletions

View File

@@ -0,0 +1,55 @@
import { safeEval } from '~/utils/safe-eval.util'
describe.only('test safe-eval', () => {
it('should eval', () => {
const res = safeEval(`return 1 + 2`)
expect(res).toBe(3)
})
it('should eval with ctx', () => {
const res = safeEval(`return a + b`, { a: 1, b: 2 })
expect(res).toBe(3)
})
it('should can not access to global or process or require', () => {
expect(() => {
safeEval(`return global`)
}).toThrow()
expect(() => {
safeEval(`return process`)
}).toThrow()
expect(() => {
safeEval(`return require`)
}).toThrow()
})
it('should can access mocked global context', () => {
const res = safeEval(`return global.a`, { global: { a: 1 } })
expect(res).toBe(1)
})
it('should can access mocked require function', () => {
const res = safeEval(`return require('fs').readFileSync('/etc/hosts')`, {
require: (name: string) => {
if (name === 'fs') {
return {
readFileSync: (path: string) => {
return ''
},
}
}
},
})
expect(res).toBe('')
})
it('should handle promise', async () => {
const promise = safeEval(
`async function handler() { return 'Hello' }; return handler()`,
)
expect(promise.__proto__.constructor.name).toBe('Promise')
expect(await promise).toBe('Hello')
})
})