简体   繁体   English

如何模拟在 Angular 中的组件声明中调用的方法?

[英]How do I mock a method that is called in my component's declaration in Angular?

I have an Angular 11 component that sets the user's timezone as a property.我有一个 Angular 11 组件,它将用户的时区设置为属性。

export class AppComponent implements OnInit {

  timezone: string =  Intl.DateTimeFormat().resolvedOptions().timeZone;

  // ...
}

This works well, I think 1 .这很好用,我认为1 Now I am trying to write a unit test for the code that uses this property.现在我正在尝试为使用此属性的代码编写单元测试。 In my spec file I have this code.在我的规范文件中,我有这个代码。

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;
  let loader: HarnessLoader;

  beforeEach(
    waitForAsync(() => {
      spyOn(Intl.DateTimeFormat(), 'resolvedOptions').and.returnValue({
        timeZone: 'America/Sao_Paulo', // this is the mocked value
        calendar: 'gregory',           // ... and the rest is just the output from Europe/London
        day: '2-digit',
        locale: 'en-GB',
        month: '2-digit',
        numberingSystem: 'latn',
        year: 'numeric',
      });

      TestBed.configureTestingModule({
        declarations: [AppComponent],
      }).compileComponents();
      fixture = TestBed.createComponent(AppComponent);
      component = fixture.componentInstance;
      loader = TestbedHarnessEnvironment.loader(fixture);
    })
  );

  describe('The User Interface', () => {
    beforeEach(async () => {
      fixture.detectChanges();
      component.ngOnInit();
    });

   it('should render timezone', () => {
      const compiled = fixture.nativeElement;
      expect(
        compiled.querySelector('.tz').textContent
      ).toContain('America/Sao_Paulo');
    });
  });
});

The code compiles, but the test fails and finds my local "Europe/London" timezone.代码编译,但测试失败并找到我当地的"Europe/London"时区。 I suspect that I am doing the mock at the wrong time.我怀疑我在错误的时间做模拟。

I thought maybe my declaration needs to live somewhere that is executed later, so I tried to move that into the constructor as well as into ngOnInit() , but neither of them changed anything.我想也许我的声明需要放在稍后执行的某个地方,所以我试图将它移到constructor以及ngOnInit()中,但它们都没有改变任何东西。

When I tried using jasmine.clock().install() and mockDate() it timed out my tests and everything broke.当我尝试使用jasmine.clock().install()mockDate()时,我的测试超时,一切都崩溃了。

How can I get that mock to work so that my component gets a fake timezone?我怎样才能让那个模拟工作,以便我的组件获得一个假的时区?


1) I should probably change my computer's timezone to check if it really does... 1)我可能应该更改计算机的时区以检查它是否确实如此......

You are setting the spy on the wrong object.您在错误的 object 上设置了间谍。 When running Intl.DateTimeFormat() you are creating a new object, both in the test and the component.运行Intl.DateTimeFormat()时,您将在测试和组件中创建一个新的 object。

You should probably spy on DateTimeFormat.您可能应该监视 DateTimeFormat。

spyOn<any>(Intl, "DateTimeFormat").and.returnValue({
    resolvedOptions: () => ({timeZone: 'MockTimezone'})
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 2-如何模拟在组件中被调用的服务? - Angular 2 - how do I mock a service being called in a component? Angular - 在组件的方法中模拟订阅 - Angular - Mock subscribe in component's method Angular Integration测试:测试发出其他组件的事件时调用的函数,如何模拟事件数据? - Angular Integration test: testing a function that is called when event from other component is emitted, how do I mock the event data? angular2 测试,我如何模拟子组件 - angular2 test, how do I mock sub component 如何使Angular 6组件继承其扩展组件的样式? - How do I get my Angular 6 components to inherit it's extended component's styles? 如何在 Angular 中模拟 HTTP 调用? - How do I mock HTTP calls in Angular? 我如何模拟Angular 2路线? - How do I Mock an Angular 2 route? 如果在所有路线上都调用了该组件,该如何隐藏导航栏(Angular4) - How can I hide my Navigation Bar if the component is called on all my routes (Angular4) 如何在角度2上创建框架的零部件? - How do I create aframe's component on angular 2? Angular 2 - 如何有条件地为我的组件添加样式? - Angular 2 - How do I conditionally add styles to my component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM