Search code examples
angulartypescripttestinguikitjestjs

Testing with UIKit and Angular


I have the following code in an angular component where declare const UIkit: any; is at the top of the file with the other imports.

When I run my tests with jest, I get the following error: ReferenceError: UIkit is not defined when the component is being created via the TestBed

Just wondering how I can point to the UIkit library during tests such that it doesn't fail.

declare const UIkit: any;

...

  ngOnInit() {
    UIkit.util.on('.sortables', 'moved', (item) => {
      // get order of blocks
      const blocks = Array.from(document.querySelectorAll('.sortable'));
      const newPositions = blocks.slice(0, blocks.length - 1).map(block => {
        return block.getAttribute('data-index');
      });

      // reorder document.blocks to match new order
      const newlyOrderedBlocks = [];
      newPositions.forEach(index => {
        newlyOrderedBlocks.push(this.document.blocks[index]);
      });
      this.document.blocks = newlyOrderedBlocks;
    });
  }

Solution

  • What ended up working for me was removing the global var declaration and declaring it as a module.

    Install @types/uikit

    uikit.ts

    declare module 'uikit';
    

    component.ts

    import * as UIkit from 'uikit';
    
    ...
    
      ngOnInit() {
        UIkit.util.on('.sortables', 'moved', (item) => {
          // get order of blocks
          const blocks = Array.from(document.querySelectorAll('.sortable'));
          const newPositions = blocks.slice(0, blocks.length - 1).map(block => {
            return block.getAttribute('data-index');
          });
    
          // reorder document.blocks to match new order
          const newlyOrderedBlocks = [];
          newPositions.forEach(index => {
            newlyOrderedBlocks.push(this.document.blocks[index]);
          });
          this.document.blocks = newlyOrderedBlocks;
        });
      }