4

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

Tamara Koliada
  • 1,222
  • 2
  • 11
  • 30
baumgarb
  • 1,416
  • 1
  • 17
  • 23
  • 3
    you are trying to write E2E test as like unit test, you should not mix two different test types, E2E is to act like human do – Lunin Roman Feb 03 '19 at 08:59
  • I see, thanks. But the question then is: is there any other / proper way to provide a fake implementation of a specific service in E2E tests? – baumgarb Feb 03 '19 at 11:57
  • I remember you did try to mock date, could you explain why do you need this? feels like not the protractor problem, but a problem with the whole approach you chose – Lunin Roman Feb 03 '19 at 12:36
  • @LuninRoman Yeah it's again about the same thing. I'd like to fake the date the whole app is based on. jasmine.clock.mockDate() is not working, so I thought abstracting 'new Date()' away into an Angular service (DateService) and faking this service for E2E tests could solve my problem. – baumgarb Feb 03 '19 at 13:42

0 Answers0