Coder Social home page Coder Social logo

maartentibau / shallow-render Goto Github PK

View Code? Open in Web Editor NEW

This project forked from getsaf/shallow-render

0.0 0.0 0.0 1.93 MB

Angular testing made easy with shallow rendering and easy mocking. https://getsaf.github.io/shallow-render

License: MIT License

JavaScript 0.41% TypeScript 99.59%

shallow-render's Introduction

shallow-render

CircleCI npm version

Angular testing made easy with shallow rendering and easy mocking.


Docs

Schematics

Articles

Angular Version Support

Angular shallow-render
17x 17x
16x 16x
15x 15x
14x 14x
13x 13x
12x 12x
11x 11x
10x 10x
9x 9x
6x-8x 8x
5x <= 7.2.0

Super Simple Tests

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

  beforeEach(() => {
    shallow = new Shallow(ColorLinkComponent, MyModule);
  });

  it('renders a link with the name of the color', async () => {
    const { find } = await shallow.render({ bind: { color: 'Blue' } });
    // or shallow.render(`<color-link color="Blue"></color-link>`);

    expect(find('a').nativeElement.textContent).toBe('Blue');
  });

  it('emits color when clicked', async () => {
    const { element, outputs } = await shallow.render({ bind: { color: 'Red' } });
    element.click();

    expect(outputs.handleClick.emit).toHaveBeenCalledWith('Red');
  });
});

The problem

Testing in Angular is HARD. TestBed is powerful but its use in component specs ends with lots of duplication.

Here's a standard TestBed spec for a component that uses a few other components, a directive and a pipe and handles click events:

describe('MyComponent', () => {
  beforeEach(async => {
    return TestBed.configureTestModule({
      imports: [SomeModuleWithDependencies],
      declarations: [
        TestHostComponent,
        MyComponent, // <-- All I want to do is test this!!
        // We either must list all our dependencies here
        // -- OR --
        // Use NO_ERRORS_SCHEMA which allows any HTML to be used
        // even if it is invalid!
        ButtonComponent,
        LinkComponent,
        FooDirective,
        BarPipe,
      ],
      providers: [MyService],
    })
      .compileComponents()
      .then(() => {
        let myService = TestBed.get(MyService); // Not type safe
        spyOn(myService, 'foo').and.returnValue('mocked foo');
      });
  });

  it('renders a link with the provided label text', () => {
    const fixture = TestBed.createComponent(TestHostComponent);
    fixture.componentInstance.labelText = 'my text';
    fixture.detectChanges();
    const link = fixture.debugElement.query(By.css('a'));

    expect(a.nativeElement.textContent).toBe('my text');
  });

  it('sends "foo" to bound click events', () => {
    const fixture = TestBed.createComponent(TestHostComponent);
    spyOn(fixture.componentInstance, 'handleClick');
    fixture.detectChanges();
    const myComponentElement = fixture.debugElement.query(By.directive(MyComponent));
    myComponentElement.click();

    expect(fixture.componentInstance.handleClick).toHaveBeenCalledWith('foo');
  });
});

@Component({
  template: '<my-component [linkText]="linkText" (click)="handleClick($event)"></my-component>',
})
class TestHostComponent {
  linkLabel: string;
  handleClick() {}
}

Whew!!! That was a lot of boilerplate. Here's just some of the issues:

  • Our TestBed module looks very similar if not identical to the NgModule I've probably already added MyComponent too. Total module duplication.
  • Since I've duplicated my module in my spec, I'm not actually sure the real module was setup correctly.
  • I've used REAL components and services in my spec which means I have not isolated the component I'm interested in testing.
    • This also means I have to follow, and provide all the dependencies of those real components to the TestBed module.
  • I had to create a TestHostComponent so I could pass bindings into my actual component.
  • My TestBed boilerplate code-length exceeded my actual test code-length.

The Solution

We should mock everything we can except for the component in test and that should be EASY. Our modules already define the environment in which our components live. They should be reused, not rebuilt in our specs.

Here's the same specs using shallow-render:

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

  beforeEach(() => {
    shallow = new Shallow(MyComponent, MyModule);
  });

  it('renders a link with the provided label text', async () => {
    const { find } = await shallow.render({ bind: { linkText: 'my text' } });
    // or shallow.render(`<my-component linkText="my text"></my-component>`);

    expect(find('a').nativeElement.textContent).toBe('my text');
  });

  it('sends "foo" to bound click events', async () => {
    const { element, outputs } = await shallow.render();
    element.click();

    expect(outputs.handleClick).toHaveBeenCalledWith('foo');
  });
});

Here's the difference:

  • Reuses (and verifies) MyModule contains your component and all its dependencies.
  • All components inside MyModule are mocked. This is what makes the rendering "shallow".
  • The tests have much less boilerplate which makes the specs easier to follow.
  • The HTML used to render the component is IN THE SPEC and easy to find.
    • This means specs now double examples of how to use your component.

shallow-render's People

Contributors

getsaf avatar dependabot[bot] avatar ike18t avatar duck-nukem avatar kylecannon avatar develobrix avatar attrobit avatar freddysilber avatar kekmeow avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.