簡體   English   中英

使用玩笑模擬時的打字稿錯誤

[英]Typescript errors when using jest mocks

我有一個先前創建的.js文件,它模擬了我們的一些函數以用於jest測試目的。 我正在將其遷移到.ts文件:

服務器.ts

const Server = jest.genMockFromModule('../Server');

Server.getAsync = Server.default.getAsync;
// other REST-ful functions here

export default Server;

我收到以下錯誤:

類型“{}”上不存在屬性“getAsync”

類型“{}”上不存在屬性“default”

然后,在相應的測試文件中:

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');
            });
    });
});

我在dispatchMock.mockImplementationOnce()上遇到錯誤

預期 1 個參數,但得到 0。(方法) jest.MockInstance<{}>.mockImplementationOnce(fn: (...args: any[]) => any): jest.Mock<{}>

...在Server.getAsync.mockReturnValueOnce

屬性 'mockReturnValueOnce' 在類型 '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...' 上不存在。

...以及在Server.getAsync.mock

屬性 'mock' 在類型 '(url: string, baseRoute?: string | null, loadingGenerator?: (isLoading: boolean) => { type: strin...' 上不存在。

我一直在努力解決這個問題,所以任何幫助都將不勝感激。

更新

好的,我將as any添加到我的Server.ts文件第一行的Server.ts ,現在看起來像:

const Server = jest.genMockFromModule('../Server') as any;

這擺脫了第一組錯誤。 仍然面臨我的.test.ts文件中的錯誤。

更新 2

我注意到,當我運行實際的 jest 測試時,即使存在 TypeErrors,它們也都通過了。 這些問題似乎與實際測試無關。

我自己解決了這個問題。 我讓它工作的方式是將任何對Server.getAsync調用Server.getAsync為特定的 jest 模擬類型。

let getAsyncMock = Server.getAsync as jest.Mock

或者

let getAsyncMock = <jest.Mock>(Server.getAsync)

這擺脫了我的錯誤。

在@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();
  });

});

使用這個

import { mocked } from 'ts-jest/utils';
import { foo } from './foo';
jest.mock('./foo');


expect(mocked(foo)).toHaveLength(1);

要覆蓋導入,您可以這樣做:

import { AnalyticsApi } from "../../api/src";

jest.mock("../../api/src");

let listPolicies = jest.fn(() => {
  return Promise.resolve();
});

(AnalyticsApi as jest.Mock<AnalyticsApi>).mockImplementation(() => ({
  listPolicies,
}));

首先,您正在使用genMockFromModule來創建Server的模擬,因此無需調用jest.mock('path/to/Server'); .

其次,你想通過做什么來實現Server.getAsync = Server.default.getAsync; ? 所做的只是將getAsync上移一個getAsync的級別。 你可以只調用jest.genMockFromModule('../Server').default; ;

dispatchMock.mockImplementationOnce()拋出該錯誤,因為您說它需要在此處傳遞一個承諾: dispatchMock.mockImplementationOnce((promise) => promise);

對於Server.getAsync.mockReturnValueOnceServer.getAsync.mock你真的想使用mocked而不是鑄造型像其他答案建議的。

示例: mocked(Server.getAsync).mockReturnValueOnce()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM