我试图在我的测试中操纵服务返回值并将该值附加到 components 字段。
所以我myService
在内部模拟Test1
并操纵它的值,true
以便它总是返回true
。通过调用fixture.detectChanges();
,我调用了应该返回的this.myService.getProperty('param');
内部并设置了also的值。但事实并非如此。该字段的值仍然是。当然失败了。PageComponent
true
myField
true
false
Test1
我不明白会发生什么。为什么我可以true
在测试中定义返回值并通过它使组件值?
测试
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { anything, instance, mock, reset, verify, when } from 'ts-mockito';
import { MyService } from '../services/myservice.service';
describe('Test', () => {
let component: PageComponent;
let fixture: ComponentFixture<PageComponent>;
let myServiceMock: myService = mock(MyService);
describe('PageComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [PageComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [
{ provide: myService, useValue: instance(myServiceMock) },
]
}).compileComponents();
fixture = TestBed.createComponent(PageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
reset(myServiceMock);
});
it('Test1 - property should be true', () => {
when(myServiceMock.getProperty(anything())).thenReturn(true);
fixture.detectChanges();
verify(myServiceMock.getProperty(anything())).once();
expect(component.isCountryInfoVisible).toBeTrue();
// Test Failed
// Expected value to be true:
// true
// Received:
// false
});
});
});
页面组件
export class PageComponent implements OnInit {
myField: boolean;
constructor(private myService: MyService) {}
ngOnInit(): void {
this.myField = this.myService.getProperty('param');
}
}
我的服务
@Injectable()
export class MyService {
private properties: Map<string, string> = new Map<string, string>();
constructor() { }
public getProperty(key: string): string {
return this.properties.get(key);
}
....
}