【问题标题】:Testing TypeScript classes with Jasmine使用 Jasmine 测试 TypeScript 类
【发布时间】:2013-12-20 17:22:04
【问题描述】:

我想问你如何测试接受另一个类的构造函数实例的类。例如我想测试方法'hasChildRoutes()':

    class Route implements ng.route.IRoute {
    public url: string;
    public config: RouteConfig;

    constructor(url: string, config: RouteConfig) {
                this.url = url;
                this.config = config;
            }

    public hasChildRoutes(): boolean {
                return this.config.childRoutes.length > 0;
            }
}

我为此编写了糟糕的单元测试(我创建了另一个类的新实例,这在我看来很糟糕):

 beforeEach(() => {
        routeSetting = new RouteSetting(1, '');
        routeConfig = new RouteConfig('', '', routeSetting, [], '');
    });


    describe('Methods test', () => {
        var childRoute: Route;

        beforeEach(() => {
            route = new Route('', routeConfig);
        });

        it('sould return false when Route has no child routes', () => {
            expect(route.hasChildRoutes()).toBeFalsy();
        });

        it('sould return true when Route has child routes', () => {
            routeConfig = new RouteConfig('', '', routeSetting, [route], '');
            route = new Route('', routeConfig);

            expect(route.hasChildRoutes()).toBeTruthy();
        });
    });

【问题讨论】:

    标签: javascript unit-testing typescript jasmine


    【解决方案1】:

    只是对这个的一些想法。

    您的测试看起来不错,但似乎没有必要以这种方式使用 beforeEach 和 afterEach。它使测试变得混乱和不可读。 就像这样:

    it('should return false when Route has no child routes', () => {
    // arrange
    routeSetting = new RouteSetting(1, '');
    routeConfig = new RouteConfig('', '', routeSetting, [], '');
    // act
    route = new Route('', routeConfig);
    // assert
    expect(route.hasChildRoutes()).toBeFalsy();
    });
    

    另外,hasChildRoutes() 不应该是 RouteConfig 的属性吗?而不是路线?

    【讨论】:

      【解决方案2】:

      在排列/动作/断言中提供依赖项实例作为 arrange 的一部分是完全有效的。

      话虽如此,如果您想单独测试a(取决于b),您可以提供一个模拟b,例如使用 sinonjs:http://sinonjs.org/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 2017-11-22
        • 1970-01-01
        • 2016-10-15
        • 2016-05-28
        相关资源
        最近更新 更多