我想對此功能進行單元測驗
供參考。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 將不一樣,我怎么能在這里寫出期望的結果?
uj5u.com熱心網友回復:
您可以使用特定的時間戳模擬 ,Date以便無論作業系統的時區如何,您的測驗用例都將通過。該new Date().getTime().toString()陳述句將始終回傳該時間戳。
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 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457273.html
上一篇:如何忽略/模擬Slf4j日志行?
