// 请问:使用jest怎么模拟JSON.parse,完成以下代码测试? "jest":"27.4.1"
// a.js
let KEY = ''
let myObj
if (localStorage.getItem('myObj')) {
myObj = JSON.parse(localStorage.getItem('myObj'))
KEY = myObj.myKey
}
export { KEY, myObj }
// jest.config.js
module.exports = {
testEnvironment: 'jest-environment-jsdom', // 模拟browser环境
}
// unit.spec.ts
import { num, KEY, myObj } from './a'
import 'jest-json'
describe('a.js', () => {
test('a.js', () => {
Object.defineProperty(window, 'localStorage', {
value: {
getItem: (key: string) => {
if (key === 'myObj') return '{"id":123,"myKey":"xxx"}'
},
},
})
Object.defineProperty(window, 'JSON', {
value: {
parse: (key: string) => {
if (key === '{"id":123,"myKey":"xxx"}') return {"id":123,"myKey":"xxx"}
},
},
})
expect(localStorage.getItem('myObj')).toBe('{"id2":123,"myKey":"xxx"}')
// 下面三个都不通过
expect(JSON.parse(localStorage.getItem('myObj') as string)).toEqual({ id2: 123, myKey: 'xxx' })
expect(KEY).toBe('xxx')
expect(myObj).toEqual({ id: 123, myKey: 'xxx' })
})
})
a.ts
文件中,处于模块作用域的代码会在该文件被其他模块导入的时候立即执行,而你想通过Object.defineProperty(window, 'localStorage', {value: /**/})
mocklocalStorage.getItem()
方法的返回值,需要在a.ts
文件被导入前进行。可以使用require()
或import()
导入a.ts
文件a.ts
:a.test.ts
:测试结果: