Reactjs 如何在日期到期之前和之后测试(使用RTL和Jest)值?

Reactjs 如何在日期到期之前和之后测试(使用RTL和Jest)值?,reactjs,jestjs,react-testing-library,Reactjs,Jestjs,React Testing Library,我有一个组件,可以获得折扣,如果折扣日期有效,那么价格会显示折扣。但是如何正确地测试这种行为呢?我有反应测试库和笑话 describe('Price', () => { beforeEach(() => { jest.resetAllMocks(); jest.useFakeTimers(); }); afterAll(() => { jest.useRealTimers(); }); it('Should not apply dis

我有一个
组件,可以获得折扣,如果折扣日期有效,那么价格会显示折扣。但是如何正确地测试这种行为呢?我有反应测试库和笑话

describe('Price', () => {
  beforeEach(() => {
    jest.resetAllMocks();
    jest.useFakeTimers();
  });
  afterAll(() => {
   jest.useRealTimers();
  });

  it('Should not apply discount after discount date is expired', () => {
    const expirationDate = new Date();
    expirationDate.setSeconds(expirationDate.getSeconds() + 10);
    const discounts = [
      {
        datetime: expirationDate.toISOString(),
        value: 10,
      },
    ];

    const { getByRole } = render(<Price value={100} discounts={discounts} />);
    const priceRow = getByRole('item', { name: /price/ });
    expect(priceRow).toHaveTextContent('$ 90,00');
    jest.advanceTimersByTime(10000);
    expect(priceRow).not.toHaveTextContent('$ 90,00');
  });
});

description('Price',()=>{
在每个之前(()=>{
jest.resetAllMocks();
开玩笑。使用faketimers();
});
毕竟(()=>{
jest.useRealTimers();
});
它('折扣日期过期后不应进行折扣',()=>{
const expirationDate=新日期();
expirationDate.setSeconds(expirationDate.getSeconds()+10);
常量折扣=[
{
datetime:expirationDate.toISOString(),
数值:10,
},
];
const{getByRole}=render();
const priceRow=getByRole('item',{name:/price/});
期望(priceRow).toHaveTextContent('90,00美元');
开玩笑提前计时(10000);
expect(priceRow).not.toHaveTextContent('$90,00');
});
});

可以使用来自的
jest.useFakeTimers('modern')
解决此问题

我的解决方案:

describe('Price', () => {
  it('Should not apply discount after discount date is expired', () => {
    jest.useFakeTimers('modern');
    const expirationDate = new Date();
    expirationDate.setSeconds(expirationDate.getSeconds() + 10);
    const discounts = [
      {
        datetime: expirationDate.toISOString(),
        value: 10,
      },
    ];
    const { getByRole } = render(<Price value={100} discounts={discounts} />);
    const priceRow = getByRole('item', { name: /price/ });
    expect(priceRow).toHaveTextContent('$ 90,00');
    jest.advanceTimersByTime(10000);
    expect(priceRow).not.toHaveTextContent('$ 90,00');
    jest.useRealTimers();
  });
});

description('Price',()=>{
它('折扣日期过期后不应进行折扣',()=>{
开玩笑的useFakeTimers(“现代”);
const expirationDate=新日期();
expirationDate.setSeconds(expirationDate.getSeconds()+10);
常量折扣=[
{
datetime:expirationDate.toISOString(),
数值:10,
},
];
const{getByRole}=render();
const priceRow=getByRole('item',{name:/price/});
期望(priceRow).toHaveTextContent('90,00美元');
开玩笑提前计时(10000);
expect(priceRow).not.toHaveTextContent('$90,00');
jest.useRealTimers();
});
});