首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jest正确地模拟重载的类型记录函数

如何使用Jest正确地模拟重载的类型记录函数
EN

Stack Overflow用户
提问于 2022-02-24 12:27:03
回答 1查看 325关注 0票数 1

我试图在一个实例上使用类型记录和Jest来模拟一个函数。然后是谷歌Auth的一个OAuth2Client。下面是我正在测试的模块:

sample.ts

代码语言:javascript
复制
import {OAuth2Client } from "google-auth-library";

export async function accessToken(): Promise<string | undefined> {
    const client: OAuth2Client = new OAuth2Client(
        "clientId", "clientSecret", "https://redirect.com"
    );
    const response = await client.getToken("code");
    return response?.tokens.access_token;
}

对于测试,我想从getToken调用返回一个固定的响应。使这变得更加复杂的是,getToken是重载的,而google-auth-library是类型记录。

代码语言:javascript
复制
getToken(code: string): Promise<GetTokenResponse>;
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
getToken(code: string, callback: GetTokenCallback): void;
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;

这是我的考验:

sample.test.ts

代码语言:javascript
复制
import { OAuth2Client } from 'google-auth-library';
import {accessToken} from "./sample";
import {GetTokenResponse} from "google-auth-library/build/src/auth/oauth2client";

type GetTokenByCode = (code: string) => Promise<GetTokenResponse>

const oAuth2Client = jest.spyOn(OAuth2Client.prototype, 'getToken') as unknown as jest.MockedFunction<GetTokenByCode>;
oAuth2Client.mockImplementation((code: string) => {
    if (code != "code") return Promise.reject("Unexpected code.");

    const response = {
        tokens: {
            refresh_token: `abc${code}`,
            access_token: "def"
        },
        res: null
    }
    return Promise.resolve(response);
});


describe('Sample', function () {
    beforeEach(() => {
        jest.resetModules();
        jest.restoreAllMocks();
    });

    it('can get a token', async () => {
        const token = await accessToken();
        expect(token).toBeDefined();
        expect(oAuth2Client).toHaveBeenCalled();
    });
});

当我运行这个测试时,我会收到以下错误--这表示客户机正在尝试真正的调用。

代码语言:javascript
复制
Error: invalid_client

    at Gaxios._request (/Users/foo/dev/token-service/node_modules/gaxios/src/gaxios.ts:158:15)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at OAuth2Client.getTokenAsync (/Users/foo/dev/token-service/node_modules/google-auth-library/build/src/auth/oauth2client.js:124:21)
    at Object.accessToken (/Users/foo/dev/token-service/src/functions/sample.ts:7:22)
    at Object.<anonymous> (/Users/foo/dev/token-service/src/functions/sample.test.ts:29:23)

查看文件.. google-auth-library/build/src/auth/oauth2client.js,似乎TS转换程序输出了一个带有签名getToken(codeOrOptions, callback)的js函数,然后调用getTokenAsync

我有点迷失在这里,我是不是在用jest.spy来嘲笑错误的过载?

EN

回答 1

Stack Overflow用户

发布于 2022-02-24 12:56:01

我相信问题是:

代码语言:javascript
复制
const client: OAuth2Client = new OAuth2Client(
  "clientId", "clientSecret", "https://redirect.com"
);

而您实际上想要模拟的是prototype父对象。

代码语言:javascript
复制
const oAuth2Client = jest.spyOn(OAuth2Client.prototype, 'getToken') as unknown as jest.MockedFunction<GetTokenByCode>;

我将尝试以下几点:

  • Nuke prototype在模拟
  • 上查看是否可以避免通过依赖注入

在被测试系统中创建实例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71251961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档