jest JSON.parse 怎么测试

// 请问:使用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' })
  })
})
阅读 1.2k
1 个回答

a.ts文件中,处于模块作用域的代码会在该文件被其他模块导入的时候立即执行,而你想通过Object.defineProperty(window, 'localStorage', {value: /**/}) mock localStorage.getItem()方法的返回值,需要在a.ts文件被导入前进行。可以使用require()import()导入a.ts文件

a.ts:

let KEY = '';
let myObj;
if (localStorage.getItem('myObj')) {
  myObj = JSON.parse(localStorage.getItem('myObj')!);
  KEY = myObj.myKey;
}
export { KEY, myObj };

a.test.ts:

test('a', () => {
  Object.defineProperty(window, 'localStorage', {
    value: {
      getItem: (key: string) => {
        if (key === 'myObj') return '{"id":123,"myKey":"xxx"}';
      },
    },
  });
  expect(localStorage.getItem('myObj')).toBe('{"id":123,"myKey":"xxx"}');

  const { KEY, myObj } = require('./a');

  expect(JSON.parse(localStorage.getItem('myObj')!)).toEqual({ id: 123, myKey: 'xxx' });
  expect(KEY).toBe('xxx');
  expect(myObj).toEqual({ id: 123, myKey: 'xxx' });
});

测试结果:

 PASS  segmentfault/1010000041462296/a.test.ts
  √ a (4 ms)
                                                                                                                                                                                                                         
Test Suites: 1 passed, 1 total                                                                                                                                                                                           
Tests:       1 passed, 1 total                                                                                                                                                                                           
Snapshots:   0 total
Time:        0.749 s, estimated 1 s
Ran all test suites related to changed files.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进