thoroc
thoroc2d ago

Stubbing @std/x

I need some help understanding how to use the stub() method with @std/x libraries.
import * as stdYaml from 'jsr:@std/yaml';

using _parse = stub(
stdYaml,
'parse',
returnsNext([{ version: '3.8' }]),
);
import * as stdYaml from 'jsr:@std/yaml';

using _parse = stub(
stdYaml,
'parse',
returnsNext([{ version: '3.8' }]),
);
The code above seems to satisfy the linter, but the test obviously fails with the following:
sh
error: MockError: Cannot stub: non-configurable instance method
throw new MockError("Cannot stub: non-configurable instance method");
sh
error: MockError: Cannot stub: non-configurable instance method
throw new MockError("Cannot stub: non-configurable instance method");
3 Replies
Leokuma
Leokuma2d ago
What you're trying to do is to mock a module's function, which is not supported. Try this workaround:
import * as stdYaml from 'jsr:@std/yaml';

using _parse = stub(
{parse: stdYaml.parse},
'parse',
returnsNext([{ version: '3.8' }]),
);
import * as stdYaml from 'jsr:@std/yaml';

using _parse = stub(
{parse: stdYaml.parse},
'parse',
returnsNext([{ version: '3.8' }]),
);
thoroc
thorocOP15h ago
That works like a charm. Shame about the lack of support natively, but at least I am unblocked. I think I might look into using external lib as I am not finding unit testing very easy using the @std libs
Leokuma
Leokuma13h ago
If the difficulties you're facing are related to mocking, stubbing and spying, feel free to open an issue at https://github.com/denoland/std/issues. Reporting your difficulties could be helpful to others

Did you find this page helpful?