import 'reflect-metadata'; import { ElementRef, } from '@angular/core'; import { DelayedClassRemovalDirective, } from './delayed-class-removal.directive'; describe('ngOnChanges', () => { // tslint:disable-next-line test('It adds the correct classes to the element', () => { const classListAdd = jest.fn(); const elementRef = { nativeElement: { classList: { add: classListAdd, }, }, } as ElementRef; const delayedClassRemovalDirective = new DelayedClassRemovalDirective( elementRef, ); delayedClassRemovalDirective.classNameConditionMap = {}; ['test', 'testOther'].forEach((className) => { delayedClassRemovalDirective.classNameConditionMap[ className ] = true; }); delayedClassRemovalDirective.ngOnChanges(); expect(classListAdd) .toHaveBeenCalledTimes(2); expect(classListAdd).toHaveBeenCalledWith( 'test', ); expect(classListAdd).toHaveBeenCalledWith( 'testOther', ); }); // tslint:disable-next-line test('It removes the correct classes to the element after a delay', () => { jest.useFakeTimers(); const classListRemove = jest.fn(); const elementRef = { nativeElement: { classList: { remove: classListRemove, }, }, } as ElementRef; const delayedClassRemovalDirective = new DelayedClassRemovalDirective( elementRef, ); delayedClassRemovalDirective.classNameConditionMap = {}; ['test', 'testOther'].forEach((className) => { delayedClassRemovalDirective.classNameConditionMap[ className ] = false; }); delayedClassRemovalDirective.ngOnChanges(); expect(setTimeout.mock.calls.length).toBe(2); expect(classListRemove).not.toBeCalled(); jest.runAllTimers(); expect(classListRemove) .toHaveBeenCalledTimes(2); expect(classListRemove).toHaveBeenCalledWith( 'test', ); expect(classListRemove).toHaveBeenCalledWith( 'testOther', ); }); // tslint:disable-next-line test('It can handle both adds and removes at the same time', () => { jest.useFakeTimers(); const classListAdd = jest.fn(); const classListRemove = jest.fn(); const elementRef = { nativeElement: { classList: { add: classListAdd, remove: classListRemove, }, }, } as ElementRef; const delayedClassRemovalDirective = new DelayedClassRemovalDirective( elementRef, ); delayedClassRemovalDirective.classNameConditionMap = { test: false, testOther: true, testTrueOther: true, }; delayedClassRemovalDirective.ngOnChanges(); expect(setTimeout.mock.calls.length).toBe(1); expect(classListAdd) .toHaveBeenCalledTimes(2); expect(classListAdd).toHaveBeenCalledWith( 'testOther', ); expect(classListAdd).toHaveBeenCalledWith( 'testTrueOther', ); expect(classListRemove).not.toBeCalled(); jest.runAllTimers(); expect(classListRemove) .toHaveBeenCalledTimes(1); expect(classListRemove).toHaveBeenCalledWith( 'test', ); }); });