Exploring the implementation of unit tests for DragDropDirective with Jest
:
import { Component } from "@angular/core";
import { TestBed } from "@angular/core/testing";
import { DragDropDirective } from "./drag-drop.directive";
@Component({
template: `<div appDragDrop></div>`,
})
class TestComponent {}
describe("DragDropDirective", () => {
let fixture: any;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [DragDropDirective, TestComponent],
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
});
it("verifying _dragInProgress is true upon drag enter or drag over", () => {
const div = fixture.nativeElement.querySelector("div");
const event = new DragEvent("dragover");
const directive = div.directive;
directive.enabled = true;
directive.handleDragOver(event);
expect(directive._dragInProgress).toBe(true);
});
it("determining _dragInProgress set to false on drag leave or drag end", () => {
const div = fixture.nativeElement.querySelector("div");
const event = new DragEvent("dragleave");
const directive = div.directive;
directive.enabled = true;
directive.handleDragEnd(event);
expect(directive._dragInProgress).toBe(false);
});
it("no change in _dragInProgress if disabled", () => {
const div = fixture.nativeElement.querySelector("div");
const event = new DragEvent("dragover");
const directive = div.directive;
directive.enabled = false;
directive.handleDragOver(event);
expect(directive._dragInProgress).toBe(false);
});
it("validating stopAndPreventDefault invocation on various drag events", () => {
const div = fixture.nativeElement.querySelector("div");
const spy = spyOn(div.directive, "stopAndPreventDefault");
const event1 = new DragEvent("dragover");
const event2 = new DragEvent("dragleave");
const directive = div.directive;
directive.enabled = true;
directive.handleDragOver(event1);
directive.handleDragEnd(event2);
expect(spy).toHaveBeenCalledTimes(2);
});
});
The initial two tests ensure that _dragInProgress
gets updated correctly when handleDragOver
and handleDragEnd
are triggered with a DragEvent
.
The third test confirms the behavior of _dragInProgress
when the directive is inactive.
The fourth test verifies the execution of stopAndPreventDefault
when specific drag-related methods are called.