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



我有一个<Price />组件,它可以收到折扣,如果折扣日期有效,那么价格会显示折扣。但如何正确地测试这种行为呢?我有React测试库和Jest。

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');
});
});

可以从这里使用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();
});
});

最新更新