kub*_*lpl 7 unit-testing node.js typescript jestjs
我正在使用 jsonwebtoken 库来验证模块中的令牌。jsonwebtoken 多次导出 verify 方法(重载)。
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;
Run Code Online (Sandbox Code Playgroud)
我的模块:
private validateToken(token: string): void {
const publicKeyToPem = this.convertPublicKeyToPEM(this.ssoPublicKey);
try {
this.decodedToken = jwt.verify(token, publicKeyToPem);
} catch (e) {
throw new Error(e);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试在单元测试中模拟验证方法。
test('should return true if token is correct', () => {
const verifyResponse = { 'test': 'test' };
jest.spyOn(jwt, 'verify').mockReturnValue(verifyResponse);
........
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误: Argument of type '{ test: string; }' 不可分配给类型为“void”的参数。ts(2345) 似乎使用了最后一个导出方法(verify)并且它返回 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)
});
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4450 次 |
| 最近记录: |