Mocking getters from babell-ed libraries
Vittly opened this issue · 6 comments
I needed to mock storiesOf
member of @storybook/react. It looked like a simple function member and all went to this code
import * as StorybookReact from '@storybook/react';
const baseStoriesOf = ImportMock.mockFunction(StorybookReact, 'storiesOf');
But it did not work. After long hours of digging, I've found out what was that. Storybook-guys use babel to compile all code. So when we do import ... from '@storybook/react'
we actually import this ugly thing:
"use strict";
require("core-js/modules/es6.object.define-property");
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "storiesOf", {
enumerable: true,
get: function get() {
return _preview.storiesOf;
}
});
// and so on
And nothing can help ImportMock.mockFunction
to replace [Getter]
.
Simplified example to reproduce the problem in gist.
Can we do something with that?
Object.defineProperty
shouldn't be an issue.
Does it work if you use import { storiesOf } from './bar'
in foo.ts
rather than import * as Module from './bar'
?
I've made a sandbox https://codesandbox.io/s/9o46016r6r?fontsize=14 for you to try.
import { storiesOf } from './bar'
No, I didn't do that. I thought there is no way to mock single member. mockFunction
takes "module" as 1st argument. Should I use something else?
Having a further look at this code, the issue is that storybook are using requirejs to configure their dependencies. Requirejs is not currently compatible with this library.
Look into storybook to see if they have unit testing resources.
Requirejs is not currently compatible with this library.
Can you please add this statement into your README. It will help people like me to save time
@Vittly Have you found out some alternative to mock babel-ed libraries like that?
Unfortunately no :(
In my case I've made it possible to replace external dependecy. Like
// my ts-module
import { CoolThing } from 'cool-external-thing';
export function f(arg1, arg2, replacerForThing = CoolThing) {
// ...
}
And in tests I do simply pass sinon.stub()
into replacerForThing
-argument. So I had to change my own code to fix the issue