Асинхронная ng-модель и ширина не возвращают начальное значение (Карма-Жасмин) - PullRequest
1 голос
/ 12 марта 2019

Я работаю над проектом AngularJS 1.7, который требует тестирования карма-жасмина.

До сих пор у меня не было проблем, пока я не протестировал компонент с ng-моделью, назначенной контроллером.Я читал, что ng-модель стала асинхронной, но я перепробовал все решения от done (), до setTimeout, $ digest и т. Д., И все еще не могу получить начальное значение ... У меня также естьта же проблема получения ширины после рендеринга компонента, из-за времени анимации

Это мой код:

component.html

<div class="test-component">
  <ul>
    <li
      style="display: inline-block; margin-bottom: 12px;"
      ng-repeat="device in $ctrl.devices | orderBy:'-numbersCount'"
    >
      <div class="test-component__container">
        <div class="test-component__progress"></div>
      </div>
      <div class="test-component__info">
        <div class="test-component__label">{{ device.label }}</div>
        <div class="test-component__numbers">
          <ng-pluralize
            class="test-component__numbers-count"
            count="device.numbersCount"
            when="{'1': '1 Number','other': '{} numbers'}"
          ></ng-pluralize>
        </div>
      </div>
      <md-switch ng-model="$ctrl.toggleObj.isActive" ng- 
      disabled="$ctrl.toggleObj.isDisabled" ng-class="[' 
      toggle__'+$ctrl.toggleObj.type]"
      aria-label="$ctrl.toggleObj.label" md-no-ink>
      </md-switch>
    </li>
  </ul>
</div>

component.controller.js

import anime from '../../../node_modules/animejs/lib/anime.es';

// CONSTANTS
const ANIMATION_DURATION = 600;
const ANIMATION_OFFSET = 500;

export class TestComponentController {
  constructor($element) {
    'ngInject';
    this.$element = $element[0];
  }

  $onInit() {
    this.devices = this.content;
    this.toggleObj = this.configuration;
    this.biggestNumber = Math.max.apply(
      Math,
      this.devices.map(function(el) {
        return el.numbersCount;
      })
    );

    this.startAnimations(this.$element, this.biggestNumber, this);
  }

  startAnimations(currentElement, highest, ctrl) {
    angular.element(() => {
      const progressBars = currentElement.querySelectorAll(
        '.test-component__progress'
      );

      // ANIMATIONS TIMELINE
      const timeline = anime.timeline({
        autoplay: true,
        easing: 'cubicBezier(0.4, 0.0, 0.2, 1)'
      });

      progressBars.forEach((element, index) => {
        if (index !== 0) {
          timeline.add(progressAnimation(element), `-=${ANIMATION_OFFSET}`);
        } else {
          timeline.add(progressAnimation(element));
        }
      });

      // Fill animation
      function progressAnimation(target) {
        return {
          targets: target,
          width: ['0%', `${(ctrl.getNumbers(target) / highest) * 100}%`],
          duration: ANIMATION_DURATION
        };
      }
    });
  }

  // Function to retrieve hostsCount for each progress bar
  getNumbers(target) {
    return Number(
      target.parentNode.nextElementSibling.children[1].innerText[0]
    );
  }
}

component.scss

@import "variables";

.test-component {
  font-weight: 600;
  font-size: 12px;
  display: table-caption;

  ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }

  .test-component__container {
    width: 280px;
    height: 6px;
    border-radius: 2px;
    box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.08);
    background-color: red;

    .test-component__progress {
      height: 6px;
      width: 0%;
      border-radius: 2px;
      background-image: linear-gradient(
        to right,
        rgba(123, 190, 51, 0.6),
        green
      );
    }
  }

  .test-component__info {
    display: flex;
    justify-content: space-between;
  }

  .test-component__label,
  .test-component__info-difference {
    line-height: 1.67;
  }

  .test-component__label {
    color: grey;
  }

  .test-component__numbers {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .test-component__numbers-count {
      text-align: right;
      color: grey;
    }

    .test-component__info-difference {
      align-items: center;
      display: flex;
      margin-left: 4px;
      color: grey;
    }

    .test-component__info-difference-icon {
      width: 16px;
      height: 16px;
      min-width: 16px;
      min-height: 16px;
      margin: 0;
    }
  }
}

component.spec.js

import angular from 'angular';
import { findAllIn } from '../../../public/test-helpers/globals';

import { TestComponentModule } from './test-compnent.module';

describe('TestComponentModule', () => {
  beforeEach(angular.mock.module(TestComponentModule.name));

  it('should exist', () => {
    expect(TestComponentModule).toBeDefined();
  });

  describe('TestComponent component', () => {
    let parentScope, element, originalTimeout;

    beforeEach(inject(($compile, $rootScope, $componentController) => {
      parentScope = $rootScope.$new();
parentScope.configuration = {
        isActive: true,
        isDisabled: false,
        type: 'active'
      };
      parentScope.content = [
        {
          label: 'first label',
          numbersCount: 4
        },
        {
          label: 'second label',
          numbersCount: 2,
        }
      ];

      element = angular.element(
        '<test-component content="content"></test-component>'
      );
      $compile(element)(parentScope);
      $componentController('TestComponent', { $element: element });

      originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
      jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

      parentScope.$digest();
    }));

    afterEach(function() {
      jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });

it('is active and not disabled according to the configuration', () => {
      const expectedActiveState = parentScope.configuration.isActive;
      const expectedDisabledState = parentScope.configuration.isDisabled;

      const activeValue = findIn(element, 'md-switch')[0].getAttribute(
        'ng-model'
      );
      const disabledValue = findIn(element, 'md-switch')[0].getAttribute(
        'ng-disabled'
      );

      setTimeout(function() {
        expect(activeValue).toEqual(expectedActiveState);
        expect(disabledValue).toEqual(expectedDisabledState);
      }, 400);
    });

    it('sets with of progress bar according to highest host', done => {
      const expectedFirstWidth = '100%'; // for the highest host;
      const expectedSecondWidth = '50%'; // for half the hosts

      setTimeout(function() {
        const progressBars = findAllIn(element, '.test-component__progress');
        const firstWidthValue = progressBars[0].style.width;
        const secondWidthValue = progressBars[1].style.width;

        expect(firstWidthValue).toEqual(expectedFirstWidth);
        expect(secondWidthValue).toEqual(expectedSecondWidth);
        done();
      }, 2500);
    });
  });
});

Полностью протестировано в браузере, включая пути и свойства элементов;Модель ng дает ложный положительный результат за то, что не сделал ();И ширина возвращается Expected '0%' to equal '100%';

Кто-нибудь тестировал ng-модель на AngularJs в этой ситуации или ему нужно было время ожидания для изменения значений?Карма-Жасмин считает, что setTimeout ожидает прохождения, но это ложные срабатывания.Спасибо

...