如何在Angular中测试延迟加载路由的存在?

时间:2020-06-19 08:33:49

标签: angular unit-testing

我的问题类似于this question。我正在尝试编写一个测试,以检查Angular中是否存在路由。链接问题的主要区别在于,我使用的是惰性加载模块而不是组件。

我有一个文件 app.routes.ts ,其中包含路线:

import { Routes } from '@angular/router';

export const routes: Routes = [
    {
        path: '',
        loadChildren: () => import('./main/main.module').then(m => m.MainModule)
    }
];

在测试文件 app.routes.spec.ts 中,我希望该路由存在:

import { routes } from './app.routes';

describe('app.routes', () => {
    it('should contain a route for /', () => {
        expect(routes).toContain({
            path: '',
            loadChildren: () => import('./main/main.module').then(m => m.MainModule)
        });
    });
});

运行此命令时,测试未通过。

期望[Object({path:``,loadChildren:Function})]包含 Object({path:'',loadChildren:Function})。错误:预期[ Object({path:'',loadChildren:Function})]包含Object({ path:'',loadChildren:Function})。 在 在UserContext上。 (http://localhost:9876/_karma_webpack_/src/app/app.routes.spec.ts:5:24) 在ZoneDelegate.invoke(http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:365:1) 在ProxyZoneSpec.onInvoke(http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1

如何修复此单元测试,并确保可以测试是否存在延迟加载的路由?谢谢!

免责声明:我知道有些人不认为这应该是单元测试的一部分,而路由应该在端到端测试中进行测试。我个人比较喜欢检查所有路线是否都存在并且没有错别字的想法。如果有人出于某种原因注释掉一条路线而忘记撤消它,而自动测试抓住了这一想法,这个想法会让我感到更加安全。

2 个答案:

答案 0 :(得分:0)

检查方式:-

    expect(routes.find((route) => JSON.stringify(route,function(key, value) {
  if (typeof value === "function") {
    return "/Function(" + value.toString() + ")/";
  }
  return value;
}) === JSON.stringify({"path":"","loadChildren":"/Function(() => import('./main/main.module').then(m => m.MainModule))/"}))).toBeTruthy();

屏幕截图有效:-

enter image description here

答案 1 :(得分:0)

基于Aakash Garg的答案,我找到了一个通用的解决方案来测试延迟加载的路由。 我正在分享我的解决方案,以防可能对遇到相同问题的人有所帮助。此解决方案对我有用,但我并没有声称这是执行此操作的理想方法。

基本上,我为茉莉花添加了一个自定义匹配器,以测试路由是否相等。

源代码文件 equal-route-matcher.ts

import MatchersUtil = jasmine.MatchersUtil;
import CustomMatcherFactories = jasmine.CustomMatcherFactories;
import CustomEqualityTester = jasmine.CustomEqualityTester;
import CustomMatcher = jasmine.CustomMatcher;
import CustomMatcherResult = jasmine.CustomMatcherResult;

function replacer(key: any, value: any) {
    if (typeof value === 'function') {
        value = value.toString();
    }
    return value;
  }

export const EqualRouteMatcher: CustomMatcherFactories = {
    toEqualRoute: (util: MatchersUtil, customEqualityTester: CustomEqualityTester[]): CustomMatcher => {
        return {
            compare: (actual: any, expected: any): CustomMatcherResult => {
                let actualstring: string, expectedstring: string;
                actualstring = JSON.stringify(actual, replacer).replace(/(\\t|\\n)/g,'');
                expectedstring = JSON.stringify(expected, replacer).replace(/(\\t|\\n)/g,'');
                if (actualstring === expectedstring) {
                    return {
                        pass: true,
                        message: 'Routes are equal'
                    };
                } else {
                    return {
                        pass: false,
                        message: 'Expected route ' + actualstring + ' to equal route ' + expectedstring
                    };
                }
            }
        };
    }
};

类型定义文件 equal-route-matcher-type.d.ts

declare namespace jasmine {
    interface Matchers<T> {
        toEqualRoute(expected: any, expectationFailOutput?: any): boolean;
    }
}

最后,您可以在单元测试文件中导入自定义匹配器,并按以下方式使用它:

import { routes } from './app.routes';
import { EqualRouteMatcher } from './equal-route-matcher.ts';

describe('app.routes', () => {
    beforeEach(() => {
        jasmine.addMatchers(EqualRouteMatcher);
    });

    it('should contain a route for /', () => {
      expect(routes.length).toEqual(1);
      expect(routes[0]).toEqualRoute({path: '',loadChildren: () => import('./main/main.module').then(m => m.MainModule)});
    });
});