【问题标题】:Unit test for url.parse callurl.parse 调用的单元测试
【发布时间】:2020-03-28 15:30:00
【问题描述】:

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

import { parse, UrlWithParsedQuery } from 'url';

export class Utils {

    public static parseUrl(url: string): UrlWithParsedQuery {
        return parse(url, true);
    }

}

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

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

【问题讨论】:

    标签: node.js typescript unit-testing jestjs


    【解决方案1】:

    它应该可以工作。

    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
    

    【讨论】:

    • 非常感谢您的回复!我没有做正确的导入。但是,当我从 'url' 使用 import url 时,我得到一个 Module '"url"' has no default export 错误。它最终适用于 import url = require('url');
    猜你喜欢
    • 2010-11-25
    • 2012-03-06
    • 2018-08-06
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多