如何在玩笑中模拟重载方法?

编程入门 行业动态 更新时间:2024-10-21 09:16:01

如何在<a href=https://www.elefans.com/category/jswz/34/1770919.html style=玩笑中模拟重载方法?"/>

如何在玩笑中模拟重载方法?

我正在使用jsonwebtoken库来验证模块中的令牌。 jsonwebtoken导出验证方法多次(重载)。

export function verify(token: string, secretOrPublicKey: Secret, options?: VerifyOptions): object | string;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    callback?: VerifyCallback,
): void;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    options?: VerifyOptions,
    callback?: VerifyCallback,
): void;

我的模块:

private validateToken(token: string): void {
        const publicKeyToPem = this.convertPublicKeyToPEM(this.ssoPublicKey);
        try {
            this.decodedToken = jwt.verify(token, publicKeyToPem);
        } catch (e) {
            throw new Error(e);
        }
    }

我试图在单元测试中模拟验证方法。

    test('should return true if token is correct', () => {

        const verifyResponse = { 'test': 'test' };
        jest.spyOn(jwt, 'verify').mockReturnValue(verifyResponse);

        ........
    });

我收到以下错误:'{test类型的参数:字符串; }'不可分配给'void'类型的参数。ts(2345)似乎使用了最后一个导出方法(验证),并且它返回void。我尝试使用jest.spyOn(jwt, 'verify').mockImplementationOnce(() => verifyResponse);似乎很好,但是如何模拟特定的重载方法?

回答如下:

代替jest.spyOn,您应该像这样使用jest.mock

const jwt = require('jwt-library');
const myMod = require('./myModule');

// it will replace all of the methods with jest.fn()
jest.mock('jwt-library')

describe('my module', () => {
  const mockDecodedToken = { 'test': 'test' };
  describe('calling a public method that calls validateToken', () => {
    beforeAll(() => {
      jwt.verify.mockReturnValue(mockDecodedToken);
      myMod.aPublicMethodThatCallsValidateToken()
    })

    it('should have called jwt.verify', () => {
      expect(jwt.verify).toHaveBeenCalledWith(
        expect.any(String)
        expect.any(Secret)
        expect.any(VerifyOptions)
      )
    })

    it('should have assigned decodedToken to my module', () => {
      expect(myMod).toHaveProperty(decodedToken, mockDecodedToken)
    });
  })
})

更多推荐

如何在玩笑中模拟重载方法?

本文发布于:2024-05-07 12:12:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:玩笑   方法   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!