programing

농담 유형 스크립트 - 모의 날짜 생성자

css3 2023. 6. 19. 21:58

농담 유형 스크립트 - 모의 날짜 생성자

나는 조롱하려고요.new Date()특정 날짜를 반환합니다.다음 코드:

const now = new Date()
jest.spyOn(global, 'Date').mockImplementation(() => now)

컴파일 오류를 표시합니다.Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'.

내 생각에 그 이유는 내가 농담을 하려고 한다고 생각하기 때문인 것 같아요.Date()대신에new Date().실제로.Date()문자열을 반환합니다.이 문제를 어떻게 해결할 수 있습니까?

글쎄요, 저는 이 해결책을 시도했고, 그것은 효과가 있었습니다.

class MockDate extends Date {
    constructor() {
        super("2020-05-14T11:01:58.135Z"); // add whatever date you'll expect to get
    }
}

그리고 각 테스트 전에 다음과 같이 추가했습니다.

// @ts-ignore
global.Date = MockDate;

이렇게 하면 내가 내부에 새로운 날짜()가 있는 함수를 호출할 때마다 위의 MockDate 클래스의 생성자에 추가한 날짜가 반환됩니다!

Arron의 답변에 대한 Daryn의 추론 코멘트는 추가 패키지 없이도 잘 작동합니다.

const mockDate = new Date();
jest.spyOn(global, "Date").mockImplementation(() => (mockDate as unknown) as string);
const myDate = new Date();

해결 방법은 모의 날짜 라이브러리를 사용하는 것이며, 이 라이브러리는 "지금"일 때 변경하는 데 사용할 수 있습니다.

const MockDate = require('mockdate');

test('Mock Date to change when "now" is', () => {
  console.log('Normal:   ', new Date().getTime());

  MockDate.set(new Date(1466424490000));

  console.log('Mocked:   ', new Date().getTime());

  MockDate.reset();

  console.log('Restored: ', new Date().getTime());
});

그리고 테스트 결과는 다음과 같습니다.

$ npm run test
> jest

 PASS  src/test.ts
  ✓ Mock Date to change when "now" is (8ms)

  console.log src/test.ts:4
    Normal:    1585505136315

  console.log src/test.ts:8
    Mocked:    1466424490000

  console.log src/test.ts:12
    Restored:  1585505136322

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.804s

GitHub의 참조 프로젝트를 참조하십시오.

컴파일러에게 듣고 싶은 것을 말하면 됩니다. 알 수 없는 문자열과 알 수 없는 문자열 다음에 나오는 문자열을 말합니다.

const now = new Date() as unknown as string

나는 조롱할 때 같은 문제가 있습니다.new Date()함수 내에서 날짜를 조롱하려고 할 때 농담 유형 스크립트를 사용합니다.

export const checkValidTime(): boolean => { 
  const now = new Date();
  const maxAllowTime = new Date('2020-02-02 09:00:00');

  console.log(`currentTime: ${now.toLocaleString()}`);
  console.log(`maxAllowTime: ${maxAllowTime.toLocaleString()}`);

  return now > maxAllowTime;
}

단위 테스트에서 모킹 솔루션:

const mockDate = new Date('2021-09-03 08:00:10');
jest
    .spyOn(global, 'Date')
    .mockImplementationOnce(() => (mockDate as unknown) as string);
const valid = checkDateTime();
expect(valid).toEqual(true);

날짜 조롱에 대한 Jest 기본 지원이 있습니다.

Jest 26.x부터 사용할 수 있습니다.

그것은 조롱할 것입니다.new Date()그리고.Date.now()결과.

사용 예:

const mockDate = new Date('2023-01-22T00:00:00.000Z')
jest.setSystemTime(mockDate)

이것은 TypeScript 유닛 테스트에서 저에게 적용됩니다. 농담으로...

const fakeNow = new Date;
jest.spyOn(global, 'Date').mockReturnValue(fakeNow);

// Anything that checks date can compare against fakeNow...

유형 스크립트를 사용하여 2023년 업데이트

// utils.ts

import { format } from 'date-fns';

export const printTimestamp = (datetime?: string | undefined) => {
  let d = new Date();
  if (datetime !== undefined) {
    d = new Date(datetime);
  }
  const date = format(d, 'dd MMMM, yyyy');
  const time = format(d, 'hh:mm');
  return `${date} at ${time}`;
};

// utils.spec.ts
import { printTimestamp } from './util';

describe('timestamp', () => {
  it('handle empty timestamp', () => {
    jest.useFakeTimers();
    jest.setSystemTime(new Date('2022-03-19 12:00:00'));
    const expected = '19 March, 2022 at 12:00';
    expect(printTimestamp()).toEqual(expected);
  });
  it('handle inputted timestamp', () => {
    const input = '2022-03-25 12:00:00';
    const expected = '25 March, 2022 at 12:00';
    expect(printTimestamp(input)).toEqual(expected);
  });
});

언급URL : https://stackoverflow.com/questions/60912023/jest-typescript-mock-date-constructor