4

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()':

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

2 Answers 2

2

It is perfectly valid for you to provide instances of dependencies as a part of arrange within arrange/act/assert.

Having said that if you want to test a (which depends on b) in isolation you can provide a mock b e.g. using sinonjs : http://sinonjs.org/

Sign up to request clarification or add additional context in comments.

Comments

0

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. 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? and not Route ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.