[英]JS: Unit testing a class function without making the actual API call?
我在 Typescript 中有一個簡單的Foo
類。 在不實際進行 API 調用的情況下進行單元測試的最佳方法是什么?
我想不出任何可以監視或存根的東西,因為我不希望它實際調用我的真實端點。 還有測試要寫嗎?
class Foo {
private _names: Array;
constructor(private _accessToken: string, private _environment: string) {}
async getInclusiveData(name: String) {
const config = {
method: "post",
headers: HEADER_INFO
};
const response = await fetch(`${baseURL}/v1/variations/match`, config);
const { results } = (await response.json()) as any;
this._names = results;
return this._names;
}
我最終做的是:
beforeEach(() => {
const fakeToken = "12345";
const env = "prod";
foo = new Foo(fakeToken, env);
getInclusiveDataSpy = sinon.spy(foo, "getInclusiveData");
});
但是為了讓那個間諜運行,我必須調用: foo.getInclusiveData()
所以感覺我並沒有真正測試任何東西
您正在測試getInclusiveData
方法,因此您不應存根和監視它。 此方法使用fetch
向遠程 API 服務器發出 HTTP 請求。 對於單元測試,我們希望我們的測試用例可以獨立運行,並且不做任何真正的 I/O 操作。 所以我們可以存根或模擬這些 I/O 和副作用操作。 我們將在您的情況下存根fetch
函數。
例如
foo.ts
:
const baseURL = 'http://localhost:3000';
export class Foo {
private _names: any[] = [];
constructor(private _accessToken: string, private _environment: string) {}
async getInclusiveData() {
const config = { method: 'post', headers: {} };
const response = await fetch(`${baseURL}/v1/variations/match`, config);
const { results } = (await response.json()) as any;
this._names = results;
return this._names;
}
}
foo.test.ts
:
import { Foo } from './foo';
import sinon from 'sinon';
describe('72721041', () => {
it('should pass', async () => {
const fakeToken = '12345';
const env = 'prod';
const foo = new Foo(fakeToken, env);
const response = {
json: sinon.stub().resolves({ results: ['a', 'b'] }),
};
(global as any).fetch = sinon.stub().resolves(response);
const actual = await foo.getInclusiveData();
sinon.assert.match(actual, ['a', 'b']);
});
});
測試結果:
72721041
✓ should pass
1 passing (6ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
foo.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.