url.parse调用的单元测试

问题描述 投票:0回答:1

我在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.
node.js typescript unit-testing jestjs
1个回答
0
投票

它应该起作用。

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
© www.soinside.com 2019 - 2024. All rights reserved.