gpt4 book ai didi

javascript - 当有多个可用时, typescript 使用不正确的类型和 Jest

转载 作者:行者123 更新时间:2023-12-03 17:24:41 26 4
gpt4 key购买 nike

我是 typescript 的新手,注意到了我没想到的行为。当我使用 js-cookie 模拟命名导入时包,它模拟属性的特定实例,但错误地选择了要使用的正确类型。

import Cookies from "js-cookie"
import { mocked } from "ts-jest/utils"

jest.mock("js-cookie")
const mockedCookies = mocked(Cookies, true)

beforeEach(() => {
mockedCookies.get = jest.fn().mockImplementation(() => "123")
})

it("SampleTest", () => {
//this line throws an error as it is using a difference interface to check against
mockedCookies.get.mockImplementationOnce(() => undefined)
//continue test...
}
@types/js-cookies有两个定义,它总是使用 get()当我将其引用为 mockCookie.get.<some-jest-function> 时的版本.因此,我收到 typescript 错误说 Type 'undefined' is not assignable to type '{ [key: string]: string; }'. .
/**
* Read cookie
*/
get(name: string): string | undefined;

/**
* Read all available cookies
*/
get(): {[key: string]: string};
我可以通过总是重新声明 jest.fn() 来解决这个问题。每次,但更喜欢使用方便的 Jest 功能(如 mockImplementationOnce)。
难道我做错了什么?有没有办法强制执行 get要使用的类型?

最佳答案

我不确定这是否有帮助,但您可以使用 mockedCookies.get.mockImplementationOnce(() => ({}))到现在为止摆脱这个错误。
更新:
经过一些测试,我看到这些模拟函数以字典样式格式存储。最后一个同名的函数总是替换前面的函数。
如果您尝试移动 get(name: string)下面get()从'js-cookie',你会看到这个错误消失了。
所以没有办法获得具有相同名称的特定功能。

关于javascript - 当有多个可用时, typescript 使用不正确的类型和 Jest ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65556421/

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