0
我試圖測試一個函數,調用連接到亞馬遜AWS的兩個其他函數。考慮到這一點,我不想調用稱爲AWS的真正函數 - 我試圖將它們存根。但是,每次運行我的測試時,它都會調用真正的函數而不是我的存根。未調用存根函數,而是調用實際版本。爲什麼?
我有點新來測試,可能會失去一些東西,但無法找到任何其他問題的解決方案。 我使用jasmine
和sinon
我的代碼如下:因爲我不
export function functionA(id: string): Promise<string> {//Return Promise<string>
//some code
return anotherFunction(id);
}
export function functionB(organizationId: string): Promise<string[]> {
//Goes to amazon do something and return Promise<string[]>
}
我省略functionA
和functionB
實施:
const cache = new Map<string, Set<string>>();
//Function to be tested - inside class XYZ
export function functionToBeTest(events: Event[]): Promise<Event[]> {
cache.clear();
let promises: Array<Promise<void>> = [];
promises = events.map((event) => {
let foundId: string;
return functionA(event.Id)
.then((id: string) => {
foundId = id;
if (!cache.has(id)) {
return functionB(id);
}
})
.then((regDev) => {
cache.set(foundId, new Set(regDev));
})
.catch((err) => {
log.error({ err: err });
return Promise.reject(err);
});
});
return Promise.all(promises)
.then(() => {
return Promise.resolve(events)
});
}
我想存根功能我不在乎他們做什麼或者我只需要將它們存根,因此我測試了functionToBeTest
內部的邏輯。
我的測試套件如下:
import * as sinon from 'sinon';
describe('testing functionToBeTest()',() => {
let stubA: sinon.SinonStub;
let stubB: sinon.SinonStub;
beforeEach(() => {
stubA = sinon.stub(xyz, 'functionA');
stubA.onFirstCall().resolves('1');
stubA.onSecondCall().resolves('2');
stubB = sinon.stub(xyz, 'functionB');
stubB.onFirstCall().resolves(['1']);
stubB.onSecondCall().resolves(['2']);
});
afterEach(() => {
stubA.restore();
stubB.restore();
});
it('should populate the cache', (done) => {
let events: Event[] = [
{
timestamp: 1,
eventType: EventType.PC,
id: '1'
},
{
timestamp: 2,
eventType: EventType.BU,
id: '2'
}
];
xyz.functionToBeTest(events)// Here should call the real function and inside it should call the stub functions
.then((result) => {
//expectations
})
.then(() => {
done();
})
.catch((err) => {
done.fail(err);
});
});
});
正如我所說的,當我運行這個測試它永遠不會調用存根函數,總是從實際函數中返回我的錯誤(應該存根)。
任何人都可以幫忙嗎?我可能做錯了存根,但我看不出有什麼問題。