gpt4 book ai didi

javascript - 我无法访问另一个模块中修改的 window.location 对象 Jest

转载 作者:行者123 更新时间:2023-11-28 03:02:52 28 4
gpt4 key购买 nike

我想模拟window.location.search

config.test.js

import config from './config'
import { MULTIPLE_VIDEOS } from './Constants/flagKeys'

describe('', () => {
const flag = { [MULTIPLE_VIDEOS]: true }

global.window = Object.create(window)

Object.defineProperty(window, 'location', {
value: {}
})

afterAll(() => {
global.window = null
})

it('Mark query string flag as true', () => {
global.window.location.search = `?${MULTIPLE_VIDEOS}=true`
expect(config.flags).toEqual(flag)
})
})

config.js

export default { flags: getFlagsFromQueryString() }

function getFlagsFromQueryString () {
const queryString = qs.parse(window.location.search.slice(1))
const flags = {}

Object.entries(queryString).forEach(([name, value]) => {
flags[name] = value.toLowerCase() === 'true'
})

return flags
}

虽然我在调用config.flags之前在位置对象中设置了搜索值,但我无法在函数内部访问它,它总是返回空字符串。

我希望 window.location.search.slice(1)getFlagsFromQueryString 函数中返回 ?multipleVideos=true 而不是空字符串,因为我更改了测试文件中的值。

我注意到一件事,当我导出函数并调用测试文件时,它可以工作。

最佳答案

对于这种类型的复杂用途。我建议您创建一个 Window 服务/util 类并从那里公开方法。易于测试和模拟。

示例:

//Window.js

class Window {
constructor(configs) {}
navigate(href) {
window.location.href = href;
}
}
export default new Window({});

现在您可以轻松模拟 Window.js。它类似于 DI 模式。

关于javascript - 我无法访问另一个模块中修改的 window.location 对象 Jest ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60826550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com