gpt4 book ai didi

unit-testing - 未调用 stub 函数,而是调用真实版本。为什么?

转载 作者:行者123 更新时间:2023-11-28 20:51:13 25 4
gpt4 key购买 nike

我正在尝试测试一个函数,该函数调用另外两个连接到亚马逊 AWS 的函数。考虑到这一点,我不想调用调用 AWS 的真实函数——我试图对它们进行 stub 。但是,每次我运行测试时,它都会调用真正的函数而不是我的 stub 。

我对测试有点陌生,可能遗漏了一些东西,但找不到任何其他问题的解决方案。我正在使用 jasminesinon

我的代码如下:

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

我要 stub 的函数:

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[]>
}

我省略了 functionAfunctionB 的实现,因为我不关心它们做了什么或者我只需要如何 stub 它们所以我测试里面的逻辑 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);
});
});
});

正如我所说,当我运行这个测试时,它从不调用 stub 函数,并且总是从真实函数(应该被 stub )内部返回错误给我。

有人可以帮忙吗?我可能做错了 stub ,但我看不出哪里出了问题。

最佳答案

发现这是一个有问题的引用。它没有调用方法 stub ,而是调用了真正的方法 stub 。为了解决这个问题,我不得不更改我的原始类,将其导出并在我想在外部使用的方法上使用 public static

关于unit-testing - 未调用 stub 函数,而是调用真实版本。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45723203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com