我是打字稿的新手,注意到了我没想到的行为。当我使用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>
. 因此,我收到打字稿错误说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
使用哪种类型?