typescript 使用玩笑模拟时的打字稿错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51215750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript errors when using jest mocks
提问by noblerare
I have a previously-created .js
file that mocks away some of our functions for jest
test purposes. I'm migrating that to a .ts
file:
我有一个先前创建的.js
文件,它模拟了我们的一些功能以进行jest
测试。我正在将其迁移到一个.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 '{}'
Property 'default' does not exist on type '{}'
类型“{}”上不存在属性“getAsync”
类型“{}”上不存在属性“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
文件第一行的末尾,现在看起来像:
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. These issues don't appear to be related to actual tests.
我注意到,当我运行实际的 jest 测试时,即使存在 TypeErrors,它们也都通过了。这些问题似乎与实际测试无关。
回答by noblerare
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
为特定的 jest 模拟类型。
let getAsyncMock = Server.getAsync as jest.Mock
or
或者
let getAsyncMock = <jest.Mock>(Server.getAsync)
This gets rid of my errors.
这摆脱了我的错误。
回答by iarroyo
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();
});
});
回答by Sean Lafferty
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,
}));
回答by ChristopherStrydom
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
which 创建了您的模拟,Server
因此无需调用jest.mock('path/to/Server');
.
Second, what are you trying to achieve by doing Server.getAsync = Server.default.getAsync;
? All that does is move the getAsync
up a level which isn't necessary. You could just call jest.genMockFromModule('../Server').default;
;
其次,你想通过做Server.getAsync = Server.default.getAsync;
什么来实现?所做的只是向上移动getAsync
一个不必要的级别。你可以打电话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()