开玩笑如何像下面这样测试 localStorage?玩笑 v27.4.1

jest how to test localStorage like below? jest v27.4.1

代码都在这里,我配置了浏览器环境,开个玩笑,如何得到num = 10?

// a.js
let num = 1
if(localStorage.getItem('setNum')){
  num = 10
}
export { num }

// unit.spec.ts
import { num } from './a'
describe('a.js', () => {
  test('num', () => {
    expect(num).toBe(10) // Expected:10  Received:1
  })
})

// jest.config.js
module.exports = {
  testEnvironment: 'jest-environment-jsdom', // mock browser environment
}

关键是模拟 localStorage.getItem() 方法及其 return 值。注意:我们需要在 import/require 模块之前进行模拟。 testEnvironment配置为jsdom.

例如

a.ts:

let num = 1;
if (localStorage.getItem('setNum')) {
  num = 10;
}
export { num };

a.test.ts:

describe('71290459', () => {
  test('should pass', async () => {
    const localStorageMock = {
      getItem: jest.fn().mockImplementation((key) => {
        if (key === 'setNum') {
          return 'fake data';
        }
        return null;
      }),
    };
    Object.defineProperty(window, 'localStorage', {
      value: localStorageMock,
    });

    const { num } = require('./a');
    expect(num).toBe(10);
  });
});

测试结果:

 PASS  Whosebug/71290459/a.test.ts
  71290459
    ✓ should pass (4 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.279 s