带有 unix 时间戳的 Typescript 单元测试

Typescript Unittest with unixtimestamp

我想对这个功能进行单元测试

仅供参考。 1. 这只是我的一部分职能。
2. paramsA, paramsB 与期望结果无关

public async mainfunction(paramsA : any, paramsB : any) {
    const unixTimestamp = new Date().getTime().toString();
    const dir = `/tmp/somethin/${unixTimestamp}`;
    return dir
}

如您所见,unixTime 将不相同 我怎样才能在这里写下预期结果?

您可以使用特定时间戳模拟 Date,这样无论 OS 的时区如何,您的测试用例都会通过。 new Date().getTime().toString() 语句将始终 returns 该时间戳。

index.ts:

export class Service {
  public async mainfunction() {
    const unixTimestamp = new Date().getTime().toString();
    return `/tmp/somethin/${unixTimestamp}`;
  }
}

index.test.ts:

import { Service } from './';

describe('71733187', () => {
  test('should pass', async () => {
    const mockDate = new Date(1466424490000);
    jest.spyOn(global, 'Date').mockReturnValue(mockDate as any);
    const svc = new Service();
    const actual = await svc.mainfunction();
    expect(actual).toEqual('/tmp/somethin/1466424490000');
  });
});

测试结果:

 PASS  Whosebug/71733187/index.test.ts
  71733187
    ✓ should pass (3 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.208 s