url.parse调用的单元测试



我在Typescript中有一个非常简单的包装器类:

import { parse, UrlWithParsedQuery } from 'url';
export class Utils {
public static parseUrl(url: string): UrlWithParsedQuery {
return parse(url, true);
}
}

如何对解析方法的调用进行单元测试?在我的单元测试中,这种方法不想起作用:

jest.spyOn('url', parse); // error: No overload matches this call.

它应该可以工作。

index.ts:

import { parse, UrlWithParsedQuery } from 'url';
export class Utils {
public static parseUrl(url: string): UrlWithParsedQuery {
return parse(url, true);
}
}

index.test.ts:

import { Utils } from './';
import url from 'url';
describe('60884651', () => {
it('should parse url', () => {
const parseSpy = jest.spyOn(url, 'parse');
const actual = Utils.parseUrl('http://stackoverflow.com');
expect(actual.href).toBe('http://stackoverflow.com/');
expect(actual.protocol).toBe('http:');
expect(parseSpy).toBeCalledWith('http://stackoverflow.com', true);
parseSpy.mockRestore();
});
});

100%覆盖率的单元测试结果:

PASS  stackoverflow/60884651/index.test.ts
60884651
✓ should parse url (10ms)
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.104s, estimated 10s

最新更新