npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@valburyakov/ngx-easy-test

v2.1.2

Published

Simplified tests for Angular 4

Downloads

7

Readme

Commitizen friendly semantic-release Awesome

ngx-easy-test

ngx-easy-test provides two extensions for Angular 4 Testing Framework:

  • a cleaner API for testing
  • a set of custom matchers

Note

Currently, it only supports Angular 4+ and Jasmine.

Introduction

Writing tests for our code is part of our daily routine. When working on large applications with many components, it can take time and effort. Although Angular provides us with great tools to deal with these things, it still requires quite a lot of boilerplate work. For this reason, I decided to create a library that will make it easier for us to write tests by cutting the boilerplate and add custom Jasmine matchers.

Installation

Using npm by running npm install @valburyakov/ngx-easy-test --save-dev

Using yarn by running yarn add @valburyakov/ngx-easy-test --dev

Example

// zippy.component.ts

@Component({
  selector: 'zippy',
  template: `
    <div class="zippy">
      <div (click)="toggle()" class="zippy__title">
        <span class="arrow">{{ visible ? 'Close' : 'Open' }}</span> {{title}}
      </div>
      <div *ngIf="visible" class="zippy__content">
        <ng-content></ng-content>
      </div>
    </div>
  `
})
export class ZippyComponent {

  @Input() title;
  visible = false;

  toggle() {
    this.visible = !this.visible;
  }
}
// zippy.component.spec.ts

import { makeHostComponentFactory, EasyTestWithHost } from 'ngx-easy-test';

describe('ZippyComponent', () => {
  let host: EasyTestWithHost<ZippyComponent>;
  
  const createHost = makeHostComponentFactory({tested: ZippyComponent});

  it('should display the title', () => {
    host = createHost(`<zippy title="Zippy title"></zippy>`);
    
    expect(host.query('.zippy__title')).toContainText('Zippy title');
  });

  it('should display the content', () => {
    host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
    
    host.trigger('click', '.zippy__title');
    
    expect(host.query('.zippy__content')).toContainText('Zippy content');
  });

  it('should display the "Open" word if closed', () => {
    host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
    
    expect(host.query('.arrow')).toContainText('Open');
    expect(host.query('.arrow')).not.toContainText('Close');
  });

  it('should display the "Close" word if open', () {
    host = createHost(`<zippy title="Zippy title">Zippy content</zippy>`);
    
    host.trigger('click', '.zippy__title');
    
    expect(host.query('.arrow')).toContainText('Close');
    expect(host.query('.arrow')).not.toContainText('Open');
  });

  it('should be closed by default', () => {
    host = createHost(`<zippy title="Zippy title"></zippy>`);
    
    expect('.zippy__content').not.toBeInDOM();
  });

  it('should toggle the content', () => {
    host = createHost(`<zippy title="Zippy title"></zippy>`);
    
    host.trigger('click', '.zippy__title');
    expect('.zippy__content').toBeInDOM();
    
    host.trigger('click', '.zippy__title');
    expect('.zippy__content').not.toBeInDOM();
  });

});

Without Host

// button.component.ts

@Component({
  selector: 'app-button',
  template: `
    <button class="{{className}}" (click)="onClick($event)">{{title}}</button>
  `,
  styles: []
})
export class ButtonComponent {
  @Input() className = 'success';
  @Input() title = '';
  @Output() click = new EventEmitter();

  onClick( $event ) {
    this.click.emit($event);
  }
}
// button.component.spec.ts

import { ButtonComponent } from './button.component';
import { EasyTest, makeTestComponentFactory } from 'ngx-easy-test';

describe('ButtonComponent', () => {

  let easyTest: EasyTest<ButtonComponent>;

  const createComponent = makeTestComponentFactory({component: ButtonComponent});

  it('should set the "success" class by default', () => {
    easyTest = createComponent();
    expect(easyTest.query('button')).toHaveClass('success');
  });

  it('should set the class name according to the [className]', () => {
    easyTest = createComponent({ className: 'danger' });
    
    expect(easyTest.query('button')).toHaveClass('danger');
    expect(easyTest.query('button')).not.toHaveClass('success');
  });

  it('should set the title according to the [title]', () => {
    easyTest = createComponent({'title': 'Click'});
    
    expect(easyTest.query('button')).toContainText('Click');
  });

  it('should emit the $event on click', function () => {
    let output;
    easyTest = createComponent();
    easyTest.whenOutput<{ type: string }>('click', result => output = result);
    
    easyTest.trigger('click', 'button', { type: 'click' });
    
    expect(output).toEqual({ type: 'click' });
  });

});

With Custom Host Component

@Component({ selector: 'custom-host', template: '' })
class CustomHostComponent {
  title = 'Custom HostComponent';
}
describe('With Custom Host Component', function () {
  let host: EasyTestWithHost<AlertComponent, CustomHostComponent>;

  const createHost = makeHostComponentFactory({tested: AlertComponent, host: CustomHostComponent});

  it('should display the host component title', () => {
    const host = createHost(`<app-alert [title]="title"></app-alert>`);
    
    expect(host.query('.alert')).toContainText('Custom HostComponent');
  });
});

Testing Directives

@Directive({
  selector: '[highlight]'
})
export class HighlightDirective {

  @HostBinding('style.background-color') backgroundColor : string;

  @HostListener('mouseover')
  onHover() {
    this.backgroundColor = '#000000';
  }

  @HostListener('mouseout')
  onLeave() {
    this.backgroundColor = '#ffffff';
  }
}
import { makeHostComponentFactory, EasyTestWithHost } from './easy-test';
import { HighlightDirective } from './highlight.directive';

describe('HighlightDirective', function () {
  let host: EasyTestWithHost<HighlightDirective>;

  const createHost = makeHostComponentFactory<HighlightDirective>(HighlightDirective);

  it('should change the background color', () => {
    host = createHost(`<div highlight>Testing HighlightDirective</div>`);
    
    host.trigger('mouseover', host.testedDe);

    expect(host.element).toHaveStyle({
      backgroundColor: '#000000'
    });

    host.trigger('mouseout', host.testedDe);

    expect(host.element).toHaveStyle({
      backgroundColor: '#ffffff'
    });
  });

});

Testing Services

import { CounterService } from './counter.service';
import { EasyTestService, createServiceFixture } from './ngx-easy-test';

describe('CounterService Without Mock', () => {
  const easyTest = createServiceFixture({service: CounterService});

  it('should be 0', () => {
    expect(easyTest.service.counter).toEqual(0);
  });
});

Testing Services With Mocks

import { CounterService } from './counter.service';
import { EasyTestService, createServiceFixture } from './ngx-easy-test';

describe('CounterService Without Mock', () => {
  const easyTest = createServiceFixture({service: CounterService, mocks: [OtherService]});

  it('should be 0', () => {
    expect(easyTest.service.counter).toEqual(0);
  });
});

Typed Mocks

import { SpyObject, mockProvider } from './ngx-easy-test';

 let otherService: SpyObject<OtherService>;
 let service: TestedService;
 
 beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        TestedService,
        mockProvider(OtherService)
      ],
    });

    otherService = TestBed.get(OtherService);
    service = TestBed.get(GoogleBooksService);
  });
  
  it('should be 0', () => {
    otherService.method.andReturn('mocked value'); // mock is strongly typed
  
   // then test serivce 
  });

API

  • makeTestComponentFactory<T>({ component : Type<T>, shallow?: booleant, ...moduleMetadata? : TestModuleMetadata } )
  • makeHostComponentFactory<T, H>({ tested : Type<T>, host?: Type<H>, moduleMetadata? : TestModuleMetadata } )
  • createServiceFixture<S>({ service : Type<S>, mocks: Type[], ...moduleMetadata? : TestModuleMetadata })
  • mockProvider<T>(type: Type<T>): Provider

Methods

  • detectChanges()
    • Run detect changes on the tested element/host
  • query(selector: string)
    • Query a DOM element from the tested element
  • queryAll(selector: string)
    • Query a DOM elements from the tested element
  • whenInput(input : object | string, inputValue? : any)
    • Change an @Input() of the tested component
  • whenOutput<T>( output : string, cb : ( result : T ) => any )
    • Listen for an @Output() of the tested component and get the result
  • trigger<T>( event : string, selector : string, eventObj = null )
    • Trigger an event on the selector element
  • dispatchCustomEvent(input: HTMLElement, eventName: string)
    • Dispatch custom event on element and detect changes
  • advance()
    • Wait a tick then detect changes

Matchers

  • toBeChecked()
    • Only for tags that have checked attribute
    • e.g. expect(this.query('input[type="checkbox"]')).toBeChecked();
  • toBeDisabled()
    • e.g. expect(this.query('.radio')).toBeDisabled();
  • toBeInDOM()
    • Checks to see if the matched element is attached to the DOM
    • e.g. expect(this.query('.ngIf')).toBeInDOM()
  • toHaveAttr({attr, val})
    • e.g. expect(this.testedElement).toHaveAttr({ attr: 'role', val: 'newRole' });
  • toHaveClass(className)
    • e.g. expect(this.query('.alert')).toHaveClass('danger');
  • toHaveStyle(style)
    • e.g. expect(this.query('.alert')).toHaveStyle({ height: '200px' });
    • Note: Colors only works with rgb(a) and hex (six numbers) values
  • toContainText(text)
    • e.g. expect(this.query('.alert')).toContainText('Text');
  • toHaveValue(value)
    • only for elements on which val can be called (input, textarea, etc)
    • e.g. expect(this.query('.input')).toHaveValue('Value!!');