【问题标题】:How to test window.location in Jest Redux如何在 Jest Redux 中测试 window.location
【发布时间】:2021-04-30 19:21:33
【问题描述】:

我的 redux 操作正在更改 window.location。不幸的是,我的尝试没有奏效。

我有一个更改 window.location 的基本操作。如果我在操作中设置控制台日志,那是正确的。

但是当我在控制台中记录操作时,这是不正确的。

screenActions.test.js

store.dispatch(actions.loadScreen())
console.log(window.location) // does not produce a string, rather the location object

screen.actions.js

export const loadScreen = () => async (dispatch, getState) => {
   ....

   window.location = 'www.google.com';
   console.log(window.location) // produces 'www.google.com'

   ....
};

任何提示或指导将不胜感激。

【问题讨论】:

  • 在我看来,您可以尝试为 window.location 定义 setter/getter 间谍,以便您知道值何时发生变化。

标签: reactjs testing redux jestjs


【解决方案1】:

来自doc

window 上的 top 属性在规范中被标记为 [Unforgeable],这意味着它是一个不可配置的自有属性,因此即使使用 Object.defineProperty,也不能被 jsdom 内运行的正常代码覆盖或隐藏。

但是,我们可以使用Object.defineProperty()window.location 定义getter/setter,并使用我们自己的属性_href。另外,你好像在使用redux-thunk中间件,loadScreen是一个异步动作创建者,你需要使用await等待异步代码完成。

例如

screen.actions.js:

export const loadScreen = () => async (dispatch, getState) => {
  window.location = 'www.google.com';
  console.log(window.location);
};

screen.actions.test.js:

import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './screen.actions';

const mws = [thunk];
const mockStore = configureStore(mws);

describe('67339402', () => {
  it('should pass', async () => {
    Object.defineProperty(window, 'location', {
      set(val) {
        this._href = val;
      },
      get() {
        return this._href;
      },
    });
    const store = mockStore({});
    await store.dispatch(actions.loadScreen());
    expect(window.location).toEqual('www.google.com');
    console.log(window.location.href); // top property on window is Unforgeable
  });
});

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'jsdom',
}

软件包版本:

"jest": "^26.6.3",

测试结果:

 PASS  examples/67339402/screen.actions.test.js (10.31 s)
  67339402
    ✓ should pass (19 ms)

  console.log
    www.google.com

      at examples/67339402/screen.actions.js:3:11

  console.log
    undefined

      at examples/67339402/screen.actions.test.js:21:13

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

【讨论】:

  • @slideshop2 感谢您抽出宝贵时间进行详细回复!非常感谢
猜你喜欢
  • 2018-06-10
  • 2020-11-28
  • 2019-03-22
  • 1970-01-01
  • 2018-09-14
  • 2017-09-23
  • 2020-09-26
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多