[英]Typescript errors when using jest mocks
I have a previously-created .js
file that mocks away some of our functions for jest
test purposes.我有一个先前创建的
.js
文件,它模拟了我们的一些函数以用于jest
测试目的。 I'm migrating that to a .ts
file:我正在将其迁移到
.ts
文件:
Server.ts服务器.ts
const Server = jest.genMockFromModule('../Server');
Server.getAsync = Server.default.getAsync;
// other REST-ful functions here
export default Server;
I am getting the following errors:我收到以下错误:
Property 'getAsync' does not exist on type '{}'
类型“{}”上不存在属性“getAsync”
Property 'default' does not exist on type '{}'
类型“{}”上不存在属性“default”
Then, in a corresponding test file:然后,在相应的测试文件中:
MyComponent.test.ts MyComponent.test.ts
import Server from 'path/to/Server';
jest.mock('path/to/Server');
const dispatchMock = jest.fn();
const getStateMock = jest.fn();
describe('MyComponent.someFunction', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('Does the right stuff', () => {
Server.getAsync.mockReturnValueOnce(Promise.resolve([{ key: 'value' }]));
dispatchMock.mockImplementationOnce((promise) => promise);
dispatchMock.mockImplementationOnce();
return someFunction()(dispatchMock)
.then(() => {
expect(Server.getAsync).toHaveBeenCalledTimes(1);
expect(Server.getAsync.mock.calls[0][0]).toBe('something');
});
});
});
I am getting errors on dispatchMock.mockImplementationOnce()
我在
dispatchMock.mockImplementationOnce()
上遇到错误
Expected 1 arguments, but got 0. (method) jest.MockInstance<{}>.mockImplementationOnce(fn: (...args: any[]) => any): jest.Mock<{}>
预期 1 个参数,但得到 0。(方法) jest.MockInstance<{}>.mockImplementationOnce(fn: (...args: any[]) => any): jest.Mock<{}>
...on Server.getAsync.mockReturnValueOnce
...在
Server.getAsync.mockReturnValueOnce
Property 'mockReturnValueOnce' does not exist on type '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...'.
属性 'mockReturnValueOnce' 在类型 '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...' 上不存在。
...and on Server.getAsync.mock
...以及在
Server.getAsync.mock
Property 'mock' does not exist on type '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...'.
属性 'mock' 在类型 '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...' 上不存在。
I've been pounding my head on this for a while so any help would be greatly appreciated.我一直在努力解决这个问题,所以任何帮助都将不胜感激。
UPDATE更新
Okay, I added as any
to the end of the first line of my Server.ts
file so now it looks like:好的,我将
as any
添加到我的Server.ts
文件第一行的Server.ts
,现在看起来像:
const Server = jest.genMockFromModule('../Server') as any;
That got rid of the first set of errors.这摆脱了第一组错误。 Still facing the errors in my
.test.ts
file though.仍然面临我的
.test.ts
文件中的错误。
UPDATE 2更新 2
I've noticed that when I run the actual jest tests, that they all pass even though there are TypeErrors.我注意到,当我运行实际的 jest 测试时,即使存在 TypeErrors,它们也都通过了。 These issues don't appear to be related to actual tests.
这些问题似乎与实际测试无关。
I fixed this myself.我自己解决了这个问题。 The way that I got it to work was to cast any calls to
Server.getAsync
to the specific jest mock type.我让它工作的方式是将任何对
Server.getAsync
调用Server.getAsync
为特定的 jest 模拟类型。
let getAsyncMock = Server.getAsync as jest.Mock
or或者
let getAsyncMock = <jest.Mock>(Server.getAsync)
This gets rid of my errors.这摆脱了我的错误。
Following the @nobleare response... a good update will be to wrap your mock implementation into the beforeAll
and clear it into the beforeEach
block:在@nobleare 响应之后……一个很好的更新是将您的模拟实现包装到
beforeAll
并将其清除到beforeEach
块中:
import { AnalyticsApi } from "../../api/src";
jest.mock("../../api/src");
describe('...', () => {
beforeAll(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
listPolicies: jest.fn().mockResolvedValue('promiseValue')
}));
});
beforeEach(() => {
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockClear();
});
});
To override an import, you can do it like so:要覆盖导入,您可以这样做:
import { AnalyticsApi } from "../../api/src";
jest.mock("../../api/src");
let listPolicies = jest.fn(() => {
return Promise.resolve();
});
(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
listPolicies,
}));
First of all, you're using genMockFromModule
which creates a mock of your Server
so there is no need to call jest.mock('path/to/Server');
首先,您正在使用
genMockFromModule
来创建Server
的模拟,因此无需调用jest.mock('path/to/Server');
. .
Second, what are you trying to achieve by doing Server.getAsync = Server.default.getAsync;
其次,你想通过做什么来实现
Server.getAsync = Server.default.getAsync;
? ? All that does is move the
getAsync
up a level which isn't necessary.所做的只是将
getAsync
上移一个getAsync
的级别。 You could just call jest.genMockFromModule('../Server').default;
你可以只调用
jest.genMockFromModule('../Server').default;
; ;
dispatchMock.mockImplementationOnce()
is throwing that error because you said it requires a promise to be passed to it here: dispatchMock.mockImplementationOnce((promise) => promise);
dispatchMock.mockImplementationOnce()
抛出该错误,因为您说它需要在此处传递一个承诺: dispatchMock.mockImplementationOnce((promise) => promise);
For Server.getAsync.mockReturnValueOnce
and Server.getAsync.mock
you actually want to use mocked
instead of casting the type like the other answers suggest.对于
Server.getAsync.mockReturnValueOnce
和Server.getAsync.mock
你真的想使用mocked
而不是铸造型像其他答案建议的。
Example: mocked(Server.getAsync).mockReturnValueOnce()
示例:
mocked(Server.getAsync).mockReturnValueOnce()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.