简体   繁体   English

使用Jasmine测试TypeScript类

[英]Testing TypeScript classes with Jasmine

i would like to ask you how can i test class that takes in constructor instance of another class. 我想问你如何测试接受另一个类的构造函数实例的类。 For example i want to test method 'hasChildRoutes()': 例如,我想测试方法'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;
            }
}

i wrote bad unit test for this (im creating new instances of another classes which is bad in my opinion): 我为此写了不好的单元测试(即时创建另一个类的新实例,这在我看来是不好的):

 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();
        });
    });

It is perfectly valid for you to provide instances of dependencies as a part of arrange within arrange/act/assert. 在arrange / act / assert中提供依赖项实例作为安排的一部分是完全有效的。

Having said that if you want to test a (which depends on b ) in isolation you can provide a mock b eg using sinonjs : http://sinonjs.org/ 话虽如此,如果你想单独测试a (这取决于b )你可以提供一个模拟b例如使用sinonjs: http ://sinonjs.org/

Just a couple of thoughts on this one. 关于这一个只是几个想法。

Your tests look fine, but it does not seem necessary to use beforeEach and afterEach in this way. 您的测试看起来很好,但似乎没有必要以这种方式使用beforeEach和afterEach。 It makes the tests confusing and un-readable. 它使测试混乱且不可读。 Rather like this: 相当于:

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();
});

Also, shouldn't hasChildRoutes() be a property of RouteConfig? 另外,hasChildRoutes()不应该是RouteConfig的属性吗? and not Route ? 而不是路线?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM