繁体   English   中英

如何在 Jest Redux 中测试 window.location

[英]How to test window.location in Jest Redux

我的 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 的 top 属性在规范中标记为 [Unforgeable],这意味着它是不可配置的自有属性,因此即使使用 Object.defineProperty,也不能被 jsdom 内运行的正常代码覆盖或遮蔽。

但是,我们可以使用Object.defineProperty()用我们自己的属性_hrefwindow.location定义 getter/setter。 另外,好像你在使用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',
}

package 版本:

"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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM