更改模拟服务值仅适用于另一个“它”

时间:2018-05-06 07:58:40

标签: javascript angular testing

我已经使用ngFor设置了一个简单组件的测试。 这是模板:

<section #menuItem
           *ngFor="let tab of tabs">
    <h2>{{tab.name}}</h2>
    <div class="settings-card">
      {{tab.content}}
    </div>
  </section>

在我的组件中,标签设置如下:

public get tabs() {
   return this.settingsMenuDataService.menuListItems.filter(item => item.show);
}

在我的spec文件中,我嘲笑服务:

const SettingsMenuDataServiceMock = {
  menuListItems: []
 }
};

{ provide: SettingsMenuDataService, useValue: SettingsMenuDataServiceMock},

现在我的it我喜欢这个:

it('', () => {
  SettingsMenuDataServiceMock.menuListItems = [
    {
      show: true
    },
    {
      show: false
    },
    {
      show: true
    }
  ];

fixture = TestBed.createComponent(SettingsComponent);
component = fixture.componentInstance;

fixture.detectChanges();

const nSections = fixture.nativeElement.querySelectorAll('section').length;
expect(nSections).toEqual(SettingsMenuDataServiceMock.menuListItems.length - 1);
});

我在nSections中得到的是0,因为在创建组件时SettingsMenuDataServiceMock.menuListItems为空。

如果我在上面的it之前添加更改,则可以正常工作:

it('', () => {
  SettingsMenuDataServiceMock.menuListItems = [
    {
      show: true
    },
    {
      show: false
    },
    {
      show: true
    }
  ];
});

it('should not add a section to the DOM if its hide property is false', () => {
  fixture = TestBed.createComponent(SettingsComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
  const nSections = fixture.nativeElement.querySelectorAll('section').length;
  console.log(nSections);
  expect(nSections).toEqual(SettingsMenuDataServiceMock.menuListItems.length - 1);
});

在这种情况下测试通过。 我的问题是:为什么它在it之间以及如何使其在相关的it内工作。

1 个答案:

答案 0 :(得分:0)

如果将它拆分为两个,它会起作用,因为在更改SettingsMenuDataServiceMock的属性后运行beforeEach。在提供之后,您无法更改您提供的某些内容的属性。

您可以将您的testsetup更改为以下内容:

const menuListItems = [];

class SettingsMenuDataServiceMock {
  get menuListItems() {
    return menuListItems;
  }
}

...

{ provide: SettingsMenuDataService, useClass: SettingsMenuDataServiceMock }

...

it('', () => {
  menuListItems = [
    {
      show: true
    },
    {
      show: false
    },
    {
      show: true
    }
  ];

  fixture = TestBed.createComponent(SettingsComponent);
  component = fixture.componentInstance;

  fixture.detectChanges();

  const nSections = fixture.nativeElement.querySelectorAll('section').length;
  expect(nSections).toEqual(SettingsMenuDataServiceMock.menuListItems.length - 1);
});