-
Notifications
You must be signed in to change notification settings - Fork 90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TypeError: _get__(...).__REWIRE__ is not a function #109
Comments
@codejet is it possible that you have a type in your code and use REWIRE instead of Rewire (https://github.com/speedskater/babel-plugin-rewire). |
thanks @speedskater, but it doesn't seem to matter whether REWIRE or Rewire...
|
I also have what appears to be the same problem:
undefined is not a constructor seems to happen when using either phantom or mocha, not sure which, but basically it's complaining because
is not a function. Note this was working fine until I reinstalled my npm modules, then it broke. |
@codejet , @robin-barnes-triptease thank you. Could one of you please create a PR with a minimum sample, similar to the ones existing in the repo? |
@codejet I am experiencing the same problem with PhantomJS but not in Chrome with karma running my tests. Did you get around fixing this? CC: @robin-barnes-triptease |
@mmahalwy no, unfortunately i didn't. we are using mocha here. |
+1 |
a colleague of mine investigated, and according to him babel-register prevents rewiring of modules living inside node_modules in our case. |
Same issue here using babel 6, mocha, karma on chrome with rc1: import * as ConfigService from "../src/services/configService";
const getEnvironmentConfigurationMock = () => Promise.resolve({});
ConfigService.__Rewire__("getEnvironmentConfiguration", getEnvironmentConfigurationMock); where configService: var environmentConfig = undefined;
export function getEnvironmentConfiguration () {
... return some form of promise
});
} |
I had the same problem, but manage to fix it. In your case @jonashartwig, it will be something like, switching: And finally in the code Hope it helps. |
Ran into this today:
Throws: I wanted to keep the
|
It seems you can't rewire a dependency that is not used. This caused the issue for me. It's a little confusing when doing TDD, cause you might want to rewire a service before anything actually uses it. // notice Foo is never used, so babel doesnt bother loading it
import Foo from "./foo"
export default class Bar {
} import Bar from "./bar"
Bar.__Rewire__('Foo', 1); // TypeError: _get__(...).__Rewire__ is not a function This can be fixed by adding a reference to the import anywhere in your code import Foo from "./foo"
Foo; // now the module will be included
export default class Bar {
} |
@spncrlkt, @ModuloM, @robin-barnes-triptease , @jonashartwig The behaviour regarding wildcard imports is intentional. The reason is that if we would add the rewire api to the wildcard import it could break the contract of modules expecting certain exports. @joshnuss You are right, rewiring a dependency which is not used or does not exist causes an error at the moment. I think we should be able to ignore such cases, as rewiring not existing dependencies won't change anything. @TheSavior what do you think? |
I am still getting this error with as simple as:
and test:
This only happens with phantomjs and only when I have export default and using babel 6:
My work around has been:
which is weird since export default should already have the apis. |
@mmahalwy maybe this could be related to the decorators in your sample. What happens if your separate the declaration of the component and the export? |
i can give it a try and report back |
@speedskater getting same problem with non decoratored file |
I found declaring an anonymous function as default export directly caused this error, whereas assigning to a const and exporting that worked. e.g.
does work
|
@asgarddesigns thanks for figuring this out. Could you please create a PR with a failing sample with your example? |
I found the same thing as @asgarddesigns. However, it is still related to the import not being used because adding a reference to the unused import fixed the problem. |
@speedskater sorry, been on holidays. Will try and push something up when I get a chance (an remember what I was actually doing!). |
I encountered an issue that may be related (version I have two modules, both of which consist of a number of exported functions. However, when I imported them, When trying to track down the difference between my modules, I discovered that while const foo = 'TEST';
export const bar = () => {
return foo;
}; It is undefined (both as a default import and as a named import) while importing this one: export const bar = () => {
return 'TEST (not Foo!)';
}; This also does not work (notice that const foo = 'bar';
export const bar = () => {
return 'TEST (not Foo!)';
}; Here is the module that I imported the three of these with: import { bar, __RewireAPI__ as RewireBar } from './bar';
console.log('bar:', bar());
console.log('rewire:', RewireBar); So it seems that you need at least one top level variable that is used within the module for I suppose that makes sense, as there would be nothing for rewire to, well, rewire, but it occurred during development and I couldn't figure out for the life of me what was happening, so if it would be possible to have a descriptive error, or simply have Let me know if this is the right place for this or if I can provide any more detail. |
@liamfd Do you still have this problem with the latest version (1.0.0-rc-4) |
@TheSavior unfortunately yes, the issue still seems to be present with |
I still got this error in 1.0 doing something like this: PushQueue.js
PushQueue.spec.js
As @mmahalwy said: When I also import the Is there some update about this issue? |
@tchock thanks for providing the sample. Could you please provide the complete code of PushQueue so that i can try to tackle the issue asap? |
@speedskater of course This is the webpack config for this: Commented the rewire code in the specs out because it didn't work. |
@tchock Thanks for providing the complete code and sorry for my delay but I have been on holidays over the last 3 weeks. I will have a look at the code tomorrow in the evening and let you know whether I can figure something out. |
@tchock I have not found your problem till now (trying to create a sample project but i think i will have to do it over the weekend). But maybe your issue is related to issue #93 and the proposed fix in the sample project danawoodman/webpack-babel-rewire-bug-example#1 |
I usually do it like this:
this usually works for me |
I got this issue also but that was because my webpack: {
isparta: {
embedSource: true,
noAutoWrap: true,
babel: {
plugins: 'rewire'
}
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
loader: 'isparta',
include: path.join(__dirname, 'src'),
exclude: /node_modules/,
}
]
}
} |
The |
Ok I got it to work! I had the plugin added to isparta and also to the babel-loader. I removed the plugin from the babel-loader and it worked. @speedskater maybe this should be added to the readme? |
@tchock Thanks for your feedback. I added it to the readme. Furthermore I created a working unit test with your sample and added it to the repository. |
@speedskater cool! I was just not aware of the babel-plugin-istanbul. Is this in any way better or better maintained? Because isparta doesn't see that much love recently. |
@tchock. Don't know which one is better maintained, but the last times i have tried babel-plugin-istanbul it worked almost out of the box while maintaining line numbers. |
@joshnuss Thanks, for the life of me I could not figure that out. |
+1 I don't thave the webpack, .babelrc config conflict. Can't use |
+1 |
just wrestled with this for an hour, if you're component exports a default && named export, make sure your default export is the one you're testing |
@ModuloM solution worked in my case. I'm using Karma with the webpack plugin, and tests are passing both in Chrome and PhantomJS. |
I also have similar issues and I'm able to fix it with solution from @ModuloM . +1 |
|
In my case, it seems like the babel is not set properly. I moved the babel setting from package.json to .babelrc, use "babel" as "inherit" and require "babel-register" then it worked. |
We've been scratching our heads on this for a couple of days now. We ran into all the same problems when trying to rewire in files that only contained exported functions. What we ran into was that But we tried adding a Babel settings are still in |
It's 2018 and @asgarddesigns's solution works! |
Just FYI, for me this problem appeared when I added non-default exports to module I was testing. For example, when it was just
it worked just fine. But when I changed it to
then I got the error. When I changed it back, the problem went away. I ended up deciding to revert to the original code, and find another way to design my code such that I would not have to export objectB. |
1. Using wildcard imports in test, then rewire-ing deps not working..
2. names imports also failing..
Also getting a.. 2. Rewire API
Also error Is there any solution to this? |
Using version: tl;drThe main 'fix' for me getting the following error:
was to use This may be an effective solution for a pile of (at least seemingly partially) related issues I seemed to come across while trying to debug this, including:
For completeness (this is a refinement on the version in my deep dive below), here is some example 'all in one' code of a full jest.mock('render', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('render')
// These are the things we want to mock
const mocks = {
collectReactComponents: jest.fn(),
}
// For all of the exports we mock above, ensure we rewire the internal module usage as well
for (const [exportName, exportMock] of Object.entries(mocks)) {
originalModule.__Rewire__(exportName, exportMock)
}
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
...mocks,
}
}) Unfortunately due to the way They do allow an 'escape hatch' for lazy loaded variables prefixed with My deep dive and eventual path to successNot sure if this is going to help anyone here.. but I was using things like the following to import: import renderReactComponents, { collectReactComponents } from 'render'
const __RenderRewireAPI__ = require('render').__RewireAPI__
console.warn('render', Object.getOwnPropertyNames(require('render')))
console.warn('render2', require('render'))
console.warn('render3', require('render').__RewireAPI__)
__RenderRewireAPI__('collectReactComponents', jest.fn()) This was giving me the following cryptic error:
And resulted in outputs like this:
So there appears to be a Changing my import to: const __RenderRewireAPI__ = require('render').__Rewire__ Appeared to get rid of the My original 'non-rewired code looked like this: const renderReactComponents = (reactComponentCollection, combinedReducers) => {
console.warn('inside-renderReactComponents', collectReactComponents)
// ...snip... But looking at the console log, we can see that that line has now been rewired to use console.warn
renderReactComponents function renderReactComponents(reactComponentCollection, combinedReducers) {
console.warn('inside-renderReactComponents', _get__("collectReactComponents")); Interestingly though, in my test file where I imported
Looking a little deeper using code like the following: console.warn('render-afterRewire-collectReactComponents', require('render').collectReactComponents)
console.warn('render-afterRewire-makeProviderWithName', require('render').makeProviderWithName) I get output like this:
Which to me looks like So I wonder if because it doesn't 'need' to be rewritten, it isn't replaced with the rewired mock, and thus we still get the original output when we import the dependency, even though all internal calls of it are rewired correctly. It could also just be that this was never a goal of rewire, which is probably fine, as we can likely get this same functionality now using the standard Working import renderReactComponents, { collectReactComponents } from 'render'
jest.mock('render', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('render')
const collectReactComponentsMock = jest.fn()
originalModule.__Rewire__(
'collectReactComponents',
collectReactComponentsMock
)
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
collectReactComponents: collectReactComponentsMock,
}
})
console.warn('render-afterRewire-alreadyImported', collectReactComponents)
console.warn('render-afterRewire-freshRequire', require('render').collectReactComponents)
renderReactComponents('aaa', 'bbb') Which ends up with the following console output, showing that things appear to have been mocked/rewired in all the places like we wanted!
So.. seemingly for me.. my biggest problem here was trying was to use |
Following on from my last comment, I found a way to abstract some of the boilerplate into a common helper function: // helpers/mock-helpers.js
export const makeMockWireFunc = (mockImportPath, mocks) => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual(mockImportPath)
// For all of the exports we mock above, ensure we rewire the internal module usage as well
for (const [exportName, exportMock] of Object.entries(mocks)) {
originalModule.__Rewire__(exportName, exportMock)
}
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
...mocks,
}
} Then in your test file/place you want to do the mocking: jest.mock('render', () =>
require('helpers/mock-helpers').makeMockWireFunc('render', {
collectReactComponents: jest.fn(),
})
) This doesn't appear to break anything Unfortunately you still have to pass the imported function (in this case, |
Running into same issue in 2020 |
got the same issue here in late 2021. What I have:
// --feautre.js --
const allFeatures = () => {
// sync function not async
}
export function getUserFeatures(user_id){
...
const results = allFeatures();
...
} I tried to rewire the allFeatures() function to return some mocked results, and no luck so far. // -- feature.test.js--
import feature from "./feature";
test('',()=>{
feature.__Rewire__("allFeatures", ()=>{
...
})
}) Error Message Version 2 // -- feature.test.js--
import * as feature from "./feature";
test('',()=>{
feature.__Rewire__("allFeatures", ()=>{
...
})
}) Error Message Version 3 // -- feature.test.js--
import {getUserFeatures, __RewireAPI__ as featureApi} from "./feature";
test('',()=>{
featureApi.__Rewire__("allFeatures", ()=>{
...
})
}) Error Message Could someone please let me know what did I do wrong? I'm deeply confused. Thanks for your time |
No matter what I try with exports and imports, I always get:
TypeError: _get__(...).__REWIRE__ is not a function
I added the plugin to our .babelrc for the tests and babel-plugin-rewire.js definitely gets executed.
I couldn't find any really similar issue. Am I missing something obvious?
The text was updated successfully, but these errors were encountered: