使用Jasmine测试TypeScript类

Testing TypeScript classes with Jasmine

本文关键字:TypeScript 测试 Jasmine 使用      更新时间:2024-02-19

我想问您如何测试接受另一个类的构造函数实例的类。例如,我想测试方法"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();
        });
    });

在arrange/act/assert中提供依赖项实例作为arrange的一部分是完全有效的。

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

关于这一点只有几个想法。

您的测试看起来不错,但似乎没有必要以这种方式使用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的属性吗?而不是Route?