#node.js #unit-testing #sinon
Вопрос:
У меня есть следующий код:
it('Should return error', async () => {
const searchMetadata = {
details: {}
};
sandbox.mock(resultService).expects('doesSearchExists').atLeast(1).resolves(true);
sandbox.mock(resultService).expects('doesSearchExists').atLeast(1).withArgs("limit").resolves(false);
sandbox.mock(analyticsService).expects('getMetadata').throws(UNABLE_TO_CALCULATE_METADATA);
await GET(request, res, (result: any) => {
expect(result).to.be.deep.equal(UNABLE_TO_CALCULATE_METADATA)
});
});
Как вы можете видеть, я пытаюсь издеваться над одной и той же функцией doesSearchExists дважды по-разному, основываясь на аргументе, который я отправил. Если отправлено ограничение, doesSearchExists должен вернуть значение false, а если ограничение отсутствует, doesSearchExists должен вернуть значение true. Но когда я пытаюсь это сделать, я получаю
TypeError: Attempted to wrap doesSearchExists which is already wrapped
есть идеи, как я могу достичь вышеперечисленного?
Комментарии:
1. Вам нужно сохранить макет и повторно использовать его для второй настройки.
Ответ №1:
Я сделал выполнимый пример, который устраняет вашу проблему.
// Employs 'mini-mocha' to emulate running in the Mocha test runner (mochajs.org)
require("@fatso83/mini-mocha").install();
const sinon = require("sinon");
const {assert} = require('@sinonjs/referee');
// The SUT
const resultService = {
doesSearchExists(arg) {}
}
describe("SO67960235", function() {
const sandbox = sinon.createSandbox();
it('Should return error <-- this title is wrong', async () => {
// setup mocks
const mock = sandbox.mock(resultService)
mock.expects('doesSearchExists').atLeast(1).resolves(true);
mock.expects('doesSearchExists').atLeast(1).withArgs("limit").resolves(false);
// call your external methods that exercise your mocks
console.log(await resultService.doesSearchExists("foo")); // true
console.log(await resultService.doesSearchExists("limit")); // false
// verify that they were called as expected
mock.verify();
});
});