Jest: $ is not defined in Angular unit testing typescript/Jquery

Viewed 241

I will be trying to write a unit test case for some angular components. so it has been thrown an error ReferenceError: $ is not defined ReferenceError: $ is not defined

we call the function in ng afterViewInit() that will use the jquery so import the npm jquery below i mention code snippet:

ngAfterViewInit() {
    $('.draggable').draggable({
      containment: '#droppable',
      helper: 'clone',
      revert: 'invalid',
      cursor: 'move',
      iframeFix: true,
      zIndex: 6,
      start: this.onAnnotationDrag.bind(this),
    });

    document.getElementById('paletteDiv').style['display'] = 'none';
    document.getElementById('annotationsDiv').style['display'] = 'block';

    this.setToolbarVisibility();

    $('.dropdown').click(function () {
      $('.dropdown-menu').toggleClass('show');
    });
  }

Unit test case:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ToolbarComponent } from './toolbar.component';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { MsAdalAngular6Service, MsAdalAngular6Module } from "microsoft-adal-angular6";
import { Constants } from '../../app.constants';
import $ from 'jquery';

jest.mock(
  'jquery',
  () => {
    const m$ = { on: jest.fn(), ready: jest.fn(), addClass: jest.fn() };
    return jest.fn(() => m$);
  },
  // remove this option if you have installed jquery module
  { virtual: true },
);

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, MsAdalAngular6Module.forRoot(Constants.ADAL_CONFIG)],
      declarations: [ToolbarComponent],
      providers: [HttpClient, MsAdalAngular6Service]
    })
      .compileComponents();
  }));

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

  it('should create', () => {
    $().ready.mockImplementationOnce((callback) => callback());
    $().on.mockImplementationOnce((event, handler) => handler());
    expect(component).toBeTruthy();
  });
});
0 Answers
Related