Error in unit testing with Jest after updating to npm 3.3.12 - node.js

I recently updated my project to node 5.1.0, npm 3.3.12 and updated all my dependencies... Now I'm fighting against a bunch of errors!
Initially I had the same error thats on this issue: https://github.com/facebook/jest/issues/554, that got easily fixed.
Bur now I'm getting this one now:
Warning: React.createElement: type should not be null, undefined,
boolean, or number. It should be a string (for DOM elements) or a
ReactClass (for composite components).
and
Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
I have this in my package.json:
"jest": {
"collectCoverage": true,
"testRunner": "./node_modules/jest-cli/src/testRunners/jasmine/jasmine2",
"scriptPreprocessor": "./node_modules/babel-jest",
"unmockedModulePathPatterns": [
"./node_modules/es6-promise",
"./node_modules/events",
"./node_modules/fbjs",
"./node_modules/flux",
"./node_modules/history",
"./node_modules/immutable",
"./node_modules/lodash",
"./node_modules/moment",
"./node_modules/react",
"./node_modules/react-addons-pure-render-mixin",
"./node_modules/react-addons-test-utils",
"./node_modules/react-d3",
"./node_modules/react-dom",
"./node_modules/react-modal",
"./node_modules/react-router",
"./node_modules/whatwg-fetch"
]
}
And the relevant parts of my tests are:
var ImageGallery = require('../../../app/components/image-gallery/image-gallery');
imageGalleryComponent = TestUtils.renderIntoDocument(
<ImageGallery
items={items}
onSlide={onSlideMock}
lazyLoad={false}
showBullets={true}
showThumbnails={true}
showNav={true}
slideInterval={4000}/>
);
Anyone ran into this issue? Any clues on how to solve it?

In my code I was using babel with "imports", so the problem was that in the tests I needed to use "imports" as well or just add a ".default" in the end of the require statement, something like this:
var ImageGallery = require('../../../app/components/image-gallery/image-gallery').default;

Related

Ambiguos "Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type" error in nexus graphql

I'm getting the following error when using nexus to define a graphql schema with apollo-server.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type
The stacktrace doesn't give much information as to where the issue is occurring or to what the problem is. The project has 20+ models and dozens of resolvers so it's quite hard to debug.
Error: NEXUS__UNKNOWN__TYPE was already defined and imported as a type, check the docs for extending types
at extendError (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1744:2)
at SchemaBuilder.addType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:603:8)
at SchemaBuilder.missingType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1212:5)
at SchemaBuilder.getOrBuildType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1540:4)
at SchemaBuilder.getOutputType (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1471:10)
at SchemaBuilder.buildOutputField (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1349:52)
at /Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1307:7
at Array.forEach (<anonymous>)
at SchemaBuilder.buildOutputFields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1306:7)
at fields (/Users/username/Documents/folder/folder/graphq-nexus-prisma-api/node_modules/nexus/src/builder.ts:1009:33)
Any help appreciated.
I got the same error, but it was because I removed some exports. I'm not exactly sure what caused it, but I basically have a file that exports all of my graphql modules. E.g.
// graphql/modules/index.ts
export * from './file-a';
export * from './file-b';
When I removed the second export line, I started getting the error. I'm probably using some of the types defined in file-b somewhere else, and that's somehow causing the error. Anyway, adding the line back in fixed it (I had removed it by accident anyway).
UPDATE
I also go this by referencing some arg types that didn't exist (typo). For example:
args: {
where: arg({ type: 'ConversationsWhereInput' }),
orderBy: arg({ type: 'ConversationsOrderByInput', list: true }),
},
The s in Conversations shouldn't be there. It should be:
args: {
where: arg({ type: 'ConversationWhereInput' }),
orderBy: arg({ type: 'ConversationOrderByInput', list: true }),
},
It could have been much helpful if you could elaborate what did you do before this error happened.
I just came up with this error exactly as same as what you got and for me it was because I just accidentally changed the name for objectType of typeDef.
For instance, the name for the FollowUserResult was actually FollowResult and after I changed the name, the whole mutation resolvers related to this objectType became wrong.
export const FollowUserResult = objectType({
name: "FollowUserResult", // It was originally "FollowResult"
definition(t) {
t.nonNull.boolean("ok");
t.string("error");
},
});
You may check on this again. Once you got those correct, delete the schema.graphql file and generate the new schema.graphql file.
I got this error because I was using the incorrect Node version. My project didn't have a .nvrmc file (yet) so I was using Node 10 on a project that uses Node 14. So after switching to the correct Node version this error went away
I got this error when I incorrectly specified an unknown type in the type attribute of an extension to the Query type. More specifically:
export const CoursesQuery = extendType({
type: "Query",
definition(t) {
t.field("myQuery", {
type: InvalidType, // <--- Changing InvalidType to the correct type fixed the error
async resolve(_parent, _args, ctx) {
return ...
},
});
},
});
The error disappeared after I changed InvalidType to the correct type and restarted the server.

Unexpected node type error SequenceExpression with jest

I was adding a snapshot test to a piece of React code, and I incurred in this error:
Unexpected node type: SequenceExpression (This is an error on an internal node. Probably an internal error. Location has been estimated.)
The code transpiles and works just fine, and the AST explorer doesn't warn me about anything.
Before this new test, no other test gave me any sort of similar error, and we have quite a few of them in our codebase.
I tried to reinstall jest, reinstall babel-jest, remove and reinstall all modules (using yarn --pure-lock), upgraded both jest and babel-jest to the latest version (20.0.1 for both), rinsed and repeated.
Nothing worked.
This occurs only when I try to collect the coverage (with --coverage), while the minimal snippet it occurs with is:
import { tint } from 'polished'
import styled from 'styled-components'
export default styled.label`
background: ${({ x, y }) => (x ? tint(0.3, y.a) : y.b)};
`
Here's what i've found:
This is an issue with jest code coverage being able to understand styled components and polished. I am using babel-plugin-polished with the following in my babelrc:
"plugins": [ "polished" ]
But still if you call export on a value, and do not also use that value in an object or exported object, it will fail.
Fails:
export const charcoalBlue = rgb(104, 131, 145);
Doesn't fail:
export const charcoalBlue = rgb(104, 131, 145);
const colors = { charcoalBlue }
So my solution has been to ignore my style files, or simply ensure I'm using the values I create and not just exporting them.
One way to ignore the style files, place this in your package.json:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!**/*.styles.js",
]
}
And name your style files {ComponentName}.styles.js
Hope this helps!
I came across the same issue!
I fixed it by working around it:
import styled, {css} from 'styled-components';
styled.label`
${({x,y}) => x
? css`background: tint(0.3, y.a);`
: css`background: ${y.b};`
}
`;

Type hints of flow not stripped by babel

I have a React.JS project which uses a custom 'theme' with UI components.
This theme also provides build scripts (webpack config, babel configs, etc.).
I want to start using Flow in this project.
I installed the needed npm packages and added flow to babel's presets, then I added props = {mytestprop: string} to one of my React` classes.
Webpack compiled my code successfully, but the type hints were not stripped! Of course, the browser was not able to execute this code - when I try to run it, it raisesReferenceError: string is not defined.
The current list of presets from .babelrc is: ["es2015", "react", "stage-2", "flow"]. I'm sure that this is the actual list used by babel because if I delete any of the first 3 presets, compilation fails.
Do you have any ideas on what could lead to this behavior when stripping Flow types?
It's not that type annotations are not being stripped. It's that { mytestprop: string } is not a valid type annotation on the right-hand side of an assignment because it clashes with the syntax for defining an object.
Specifically, when Flow's parser sees the statement { mytestprop: string } it will interpret this as an attempt to create an object with a field named mytestprop with its value set to the value of the variable string, so it will leave the statement alone as it is, and you'll get the error you've seen in the browser.
The correct way to type object declarations is to type the left-hand side of the declaration.
For instance,
let myProps: { myTestProp: string } = { myTestProp: "testProp" };
if you aren't declaring your props separately, you could declare a custom type:
type myPropType = { myTestProp: string }
// ...
const myComponent = (props: myPropType) => //render your component
Since the type statement is exclusive to Flow and not a valid JavaScript statement, it will be stripped correctly.

"Cannot GET /" error using Roots - CoffeeScript

I am using Roots to develop an app, as I run roots watch command, then it compiles successfully and opens the localhost:1111 page, but with the error below:
Cannot GET /
This is how my app.coffee file looks like, though I looked for a fix for this in SOF and none of them seemed to work for this case.
axis = require 'axis'
rupture = require 'rupture'
autoprefixer = require 'autoprefixer-stylus'
js_pipeline = require 'js-pipeline'
css_pipeline = require 'css-pipeline'
module.exports =
ignores: ['readme.md', '**/layout.*', '**/_*', '.gitignore', 'ship.*conf']
extensions: [
js_pipeline(files: 'assets/js/*.coffee'),
css_pipeline(files: 'assets/css/*.styl')
]
stylus:
use: [axis(), rupture(), autoprefixer()]
sourcemap: true
'coffee-script':
sourcemap: true
jade:
pretty: true
Is it a different solution since this is CoffeeScript instead of JS?
So it turns out to be the fact that I needed to cd project-name after I have done roots new project-name, and then only roots watch would work.
Such a rookie mistake, but a good lesson.

How to make Backbone-Relational (0.8.5) work with RequireJS?

After another long research, sth comes out :-) It seems the problem is about the function "getObjectByName". It can not work well with requireJS(ADM). Currently, I have to setup a globel var to fix the problem. I am sure there must be have better solution.
Here is my temp soluton:
(1) setup a global var and setup the search model scope to the global ("APP")
var APP = {};
define(['backbone-relational'], function(){
Backbone.Relational.store.addModelScope(APP);
})
(2) export your relation model to the global
APP.YourRelationalModel = YourRelationModel;
It works, not good though... I'm really looking forward to a better answer. Thanks.
//------------
test versions:
1.Backbone-Relational 0.8.5
2.Backbone 1.0.0 and Underscore 1.4.4
3.JQuery 1.8.3
4.RequireJS 2.1.5
Code is very simple: (or see https://github.com/bighammer/test_relational_amd.git)
require.config({
paths : {
js : 'js',
jquery : 'js/jquery-1.8.3',
underscore : 'js/underscore',
backbone : 'js/backbone',
'backbone-relational' : 'js/backbone-relational'
},
shim : {
underscore : {
exports : '_'
},
backbone : {
deps : ['underscore', 'jquery'],
exports : 'Backbone'
},
'backbone-relational' : {
deps: ['backbone']
}
}
});
define(['backbone', 'backbone-relational'], function (Backbone) {
var Child = Backbone.RelationalModel.extend();
var Parent = Backbone.RelationalModel.extend({
relations : [
{
key : 'child',
type : Backbone.HasOne,
relatedModel : 'Child'
}
]
});
var test = new Parent();
});
save above code in main.js and included in index.html as follows:
It doesn't work. There is warning message:
Relation=child: missing model, key or relatedModel (function (){ return parent.apply(this, arguments); }, "child", undefined).
I read the source code of backbone-relational and know there is something wrong with the namespace. Relational-Backbone cannot find the relatedModel defined in "Parent" (i.e. cannot find releatedMode:"Child"). I failed to find the solution to fix this due to my limited knowledge of javascript :-)
Can anyone help me with this?
Before I asked my question, I studied the following solutions:
Backbone.RelationalModel using requireJs
Can't get Backbone-relational to work with AMD (RequireJS)
Loading Backbone.Relational using Use! plugin
None of them worked in this case.
You don't have to reference relatedModel by string, you can reference it directly, so instead of relatedModel: 'Child', just use: relatedModel: Child.
And since you are using requireJS, you can reference model from other file easily.
define(['backbone', 'models/child', 'backbone-relational'], function (Backbone, Child) {
var Parent = Backbone.RelationalModel.extend({
relations : [{
key : 'child',
type : Backbone.HasOne,
relatedModel : Child
}]
});
var test = new Parent();
});
The above solution didn't apply to me. I am gradually moving code out of Rails Asset Pipeline (not RequireJS/AMD/CommonJS/anything) into Webpack, starting with dependencies. When I moved requiring backbone-relational into Webpack bundle preparation by my models and relation definitions were still in Rails Asset Pipeline, I started getting a lot of unexplained Relation=child: missing model, key or relatedModel (function (){ return parent.apply(this, arguments); }, "child", undefined).
In my case, the solution ended up being quite simple, despite taking a long time to discover on my part:
// In a Webpack module, later included into Rails Asset Pipeline
// temporarily to facilitate migration
require('expose?Backbone!backbone') // Exposing just for migration
require('backbone-relational')
Backbone.Relational.store.addModelScope(window)
backbone-relational by default uses its global scope to resolve string-based relatedModels but since it was required without a real global scope, the solution is simply to pass that in using addModelScope so it can search that scope for the specified models.

Resources