I have the following code:
describe('run()', () => {
const ret = ['returnValue'];
const expectedData = 'data';
beforeEach(() => {
sinon.stub(myStubbedService, 'myStubbedMethod').resolves(ret);
});
it('should not break', async () => {
const foo = myStubbedService.myStubbedMethod();
const bar = await myStubbedService.myStubbedMethod();
const works = Buffer.from(bar[0], 'hex');
console.log(works);
const breaks = Buffer.from(await myStubbedService.myStubbedMethod()[0], 'hex');
console.log(breaks);
})
logging works
logs the correct Buffer but logging breaks
=>
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
I am pretty sure the code for breaks
works just the same as the code for works
but the test fails. What am I missing?
Actually, your way to get the works
is not the same as breaks
. The way to get the works
is easy to understand - Wait for the response of myStubbedMethod
, then get the first item of the response.
Take a look at the way you get the breaks
:
const breaks = Buffer.from(await myStubbedService.myStubbedMethod()[0], 'hex');
(Maybe) as you know myStubbedService.myStubbedMethod()
return a Promise
, when you get the 0
attribute of a Promise, you get back an undefined value.
await
with a constant, you get the constant.
Your code will look like this:
const breaks = Buffer.from(await undefined, 'hex');
Just more parentheses:
const breaks = Buffer.from((await myStubbedService.myStubbedMethod())[0], 'hex');