Home > Enterprise >  Typescript Unittest with unixtimestamp
Typescript Unittest with unixtimestamp

Time:04-07

I want to make a unit test for this function

FYI. 1. This is just a part of my function.
2. paramsA, paramsB not related to expect result

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

as you can see unixTime won't be the same how can i write the expect result here ?

CodePudding user response:

You can mock the Date with a specific timestamp so that your test case will pass no matter the timezone of the OS. The new Date().getTime().toString() statement will always returns that timestamp.

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

Test result:

 PASS  stackoverflow/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
  • Related