puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Test for a simple routerLink in Angular #51

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

In Angular we sometimes need to write test for simple routerLink.

e.g.

describe('DummyComponent', () => { let component: DummyComponent; let fixture: ComponentFixture;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [
            DummyComponent,
        ],
        imports: [ RouterTestingModule ],
    })
        .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(DummyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () => {
    expect(component).toBeTruthy();
});

it('should go to "/" url', () => {
    const debugElements = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref));   <=====
    const index = debugElements.findIndex((de) => {
        const href = 'href';
        return de.properties[href] === '/';      <====
    });
    expect(index).toBeGreaterThan(-1);
});

});


👉  Notice here, 
const href = 'href';
return de.properties[href] === '/';

needs to use a variable for the string into the method, otherwise it will have a TSLint error. [2]

```diff
- Error:(32, 34) TSLint: object access via string literals is disallowed (no-string-literal)

Reference

[1] https://stackoverflow.com/questions/39577920/angular-2-unit-testing-components-with-routerlink [2] https://stackoverflow.com/questions/33387090/how-to-rewrite-code-to-avoid-tslint-object-access-via-string-literals