I'm having troubles when trying to spy on a service's method so that I can return a faked value in an Angular E2E
test with Protractor
.
This is the component (loaded when the route '/date' is hit):
@Component({
selector: 'app-date',
template: `
Current date is <span class="e2e-curr-date">{{currentDate | date:'yyyy-MM-dd'}}</span>
`,
})
export class DateComponent implements OnInit {
currentDate: Date;
constructor(private dateSvc: DateService) {}
ngOnInit() {
this.currentDate = this.dateSvc.getCurrentDate();
}
}
And this is the corresponding E2E test:
describe('workspace-project App', () => {
const homePage = new HomePage();
const datePage = new DatePage();
beforeAll(() => {
spyOn(DateService.prototype, 'getCurrentDate').and.returnValue(new Date(2040, 0, 1));
});
it('should display the fake date put in place via a fake date service', async () => {
await homePage.navigateTo();
await homePage.isLoaded();
await datePage.navigateTo();
await datePage.isLoaded();
const result = await datePage.getCurrentDateDisplayed();
expect(result).toEqual('2040-01-01');
});
});
This test always fails with the error message :
Expected '2019-02-03' to equal '2040-01-01'. So it's displaying the current date rather than the one which should be returned by the spy-setup.
You can find the full working code sample here: https://github.com/baumgarb/ng-mock-date-in-e2e-tests