[英]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.