stencil icon indicating copy to clipboard operation
stencil copied to clipboard

feat: Abblility to mock the current date

Open ryuran opened this issue 2 years ago • 2 comments

Prerequisites

Describe the Feature Request

For test purpose we need to fake the current date.

Describe the Use Case

For test purpose we need to fake the current date.

We work on a calendar component and use screenshot tests. Sadly each time we run test and the current date changed, the component will render differently and it's expected.

It's why we need to fixe a date to run a test on it.

We tested :

  • to proxy the Date object in the browser without success.
  • to use jest.useFakeTimers('modern').setSystemTime(…) but we encounter a bunch of Timeout errors in e2e tests

Describe Preferred Solution

Don't have a preference :

  • parameter in newE2ePage to set a date as "now"
  • a way to reach the puppeteer browser before to run a page

Describe Alternatives

No response

Related Code

No response

Additional Information

No response

ryuran avatar Mar 18 '22 19:03 ryuran

This is still an issue in Stencil v3. More generally, it looks like there isn't a way to mock out calls to setInterval, setTimeout, etc using Jest timer mocks. Rendering a component using the newSpecPage helper times out if we're using timer mocks with jest.userFakeTimers().

I created a new project using npm init stencil and copied over the "CurrentTime" component implementation from this example on the Stencil docs, which uses setInterval and Date.now() to display the current time each second. I added the following unit test, which times out.

import { newSpecPage } from '@stencil/core/testing';
import { CurrentTime } from '../current-time';

describe('current-time', () => {
  it('renders', async () => {
    jest.useFakeTimers(); // if this line is removed test runs successfully

    // test times out here
    const page = await newSpecPage({
      components: [CurrentTime],
      html: `<current-time></current-time>`,
    });

    let displayedTime = page.root.querySelector("span").innerText;
    expect(displayedTime).toBeDefined();
  });
});

I did try upgrading to the latest Stencil version (3.2.0) but saw the same behavior.

cmardyla avatar Mar 29 '23 16:03 cmardyla

@cmardyla can reproduce this behaviour. I'm unable to test a component with useFakeTimers in stencil.

fschoenfeldt avatar Apr 30 '24 12:04 fschoenfeldt