I have encountered an issue while trying to manipulate the service return value in my test and assign that value to a component's field.
During the test, I mock the myService
within the Test1
and set its return value to true
so that it always returns true
. After calling fixture.detectChanges();
, I trigger
this.myService.getProperty('param');
within the PageComponent
expecting it to return true
and update the value of myField
to true
as well. However, this does not happen as expected; the field value remains false
, causing Test1
to fail.
I am confused about why setting the return value to true in the test is not reflecting in the component's value. Can someone help me understand what might be going wrong?
Test
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
});
});
});
PageComponent
export class PageComponent implements OnInit {
myField: boolean;
constructor(private myService: MyService) {}
ngOnInit(): void {
this.myField = this.myService.getProperty('param');
}
}
MyService
@Injectable()
export class MyService {
private properties: Map<string, string> = new Map<string, string>();
constructor() { }
public getProperty(key: string): string {
return this.properties.get(key);
}
....
}