How to write Angular Jasmine simple 'should create' test case using shallow-render instead of using NO_ERRORS_SCHEMA

痴心易碎 提交于 2020-01-04 07:01:52

问题


I have a few angular (v6) components whose template contains RouterLink reference. These components have the default generated test case entitled 'should create', which breaks with the error:

Can't bind to 'routerLink' since it isn't a known property of 'a'. ("12">

I can fix this using NO_ERRORS_SCHEMA, for example:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ NotFoundComponent ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

But the problem with using this method is that it is a bit too brutal and hides all errors with the template (as I discovered reading this question: Problems with Angular's NO_ERRORS_SCHEMA?)

This question contains various solutions, 1 of which requires the use of a testing helper library called shallow-render.

I need to find out how to write the equivalent 'should create' test case using shallow-render instead of NO_ERROR_SCHEMA. The examples documented do not cover this scenario, so I have just tried to experiment using the other examples as appropriate. Here is my code:

COMPONENT:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'apclib-lock',
  templateUrl: './lock.component.html',
  styleUrls: ['./lock.component.css']
})
export class LockComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

COMPONENT SPEC:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { LockComponent } from './lock.component';
import { Shallow } from 'shallow-render';
import { AuthenticationModule } from '../authentication.module';

describe('LockComponent', () => {
  let component: LockComponent;
  let fixture: ComponentFixture<LockComponent>;
  let shallow: Shallow<LockComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LockComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LockComponent);
    component = fixture.componentInstance;
    shallow = new Shallow<LockComponent>(LockComponent, AuthenticationModule);
    fixture.detectChanges();
  });

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

TEMPLATE:

<section id="wrapper">
  <div class="login-register" style="background-image:url(../assets/images/background/login-register.jpg);">
    <div class="login-box card">
      <div class="card-body">
        <form class="form-horizontal form-material" id="loginform" action="index.html">

          <div class="form-group text-center">
            <div class="col-xs-12">
              <a class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" [routerLink]="['/dashboard/dashboard1']">Log In</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</section>

ERROR:

Chrome 67.0.3396 (Mac OS X 10.13.5) LockComponent should create FAILED Can't bind to 'routerLink' since it isn't a known property of 'a'. ("12"> ][routerLink]="['/dashboard/dashboard1']">Log In "): ng:///DynamicTestModule/LockComponent.html@21:95

I am trying to do things the right way, and brutally hiding template errors using NO_ERRORS_SCHEMA does not seem the right thing to do, so I just need to find out how to get rid of that error for a simple creational test case using shallow-render.

PS: in https://github.com/getsaf/shallow-render/wiki/Examples it would have been nice to see an example entitled 'component with RouterLink' as this is a common error experienced by other devs and is the main reason for me trying to switch to shallow-render.


回答1:


It looks like you're attempting to use a combination of Shallow and TestBed. Shallow is a replacement for TestBed. The good news is that this makes tests much easier to write.

import { Shallow } from 'shallow-render';
import { LockComponent } from './lock.component';
import { AuthenticationModule } from '../authentication.module';

describe('LockComponent', () => {
  let shallow: Shallow<LockComponent>;

  beforeEach(() => {
    shallow = new Shallow<LockComponent>(LockComponent, AuthenticationModule);
  });

  it('should create', async () => {
    const {instance} = await shallow.render();

    expect(instance).toBeTruthy();
  });
});

Side note: I'm not a big fan of Angular's "should create" default test because they don't actually exercise the component or verify any of it's behavior. I definitely recommend testing component behavior instead of simple creation tests.

If you're interested in testing the behavior of the link, the RouterModule can be a little weird and you may want/need to use Angular's RouterTestingModule. If you go that route, I have an example spec on the official StackBlitz that you can reference. I just updated it to use the RouterLinkDirective after reading this question.



来源:https://stackoverflow.com/questions/51198288/how-to-write-angular-jasmine-simple-should-create-test-case-using-shallow-rend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!