I am following instructions for updating Expo from 46 to 47. Overall it's going well, however, a Jest test is failing when trying to read my app.config's API_URL environment variable:
my jest config is using:
preset: 'jest-expo',
const API_URL = Constants?.manifest?.extra?.api;
I read:
With SDK 46, one notable change was to move from Constants.manifest.extra to Constants.expoConfig.extra.
const API_URL = Constants?.expoConfig?.extra?.api;
However, the result is still undefined
What could have changed from SDK 46 to 47 causing this failure?
I have also tried mocking the expo-constants library:
jest.mock('expo-constants', () => {
return {
extra: {
api: 'myfull URL',
},
};
});
And this also does not seem to have an impact on the output. Thanks for clarifications
Related
I am running into an issue where I am running multiple tests using supertest and jest. When there is only one test running then it works just fine but the second one throws the following error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
I tested this with two very simple tests:
describe("Default API", () => {
describe("Default:", () => {
it("should create a user in the DB", (done) => {
request(app).get("/").expect(200, done);
});
it("should create a user in the DB", (done) => {
request(app).get("/").expect(200, done);
});
});
});
They are the same but the second one throws the error. If I run only the first one there is no issue. This must be a setup issue Does anyone have advice. In my index.ts where I have the main express code I export app as follows:
export default app;
This is at the bottom of the index.ts file.
I had the simular problem and toggle down the issue, in my case I want to use mysql2 to access mariadb. That Module try to autodetect the charset and do to try to lacy loading that encoding.
But I have not found a solution for that for now.
I am using for the first time the aurelia-testing package to test my HTML code.
I seem to have followed the docs to set up my test as follows:
describe('Contextual Menu HTML View test suite', function () {
let component: ComponentTester;
beforeEach(function () {
component = StageComponent
.withResources('../../src/components/modal/contextual-menu')
.inView('<contextual-menu is-active.two-way="activateMenu"></contextual-menu>')
.boundTo({ activateMenu: false });
});
it('should not add the is-active class to the root element', async function () {
await component.create(bootstrap);
const rootElement = await waitForDocumentElement('.qa-contextual-menu');
expect(rootElement.classList.contains('is-active')).toBe(false);
});
afterEach(function () {
component.dispose();
});
});
I tried using just bind instead of two-way but that fails too.
I tried both with a document.querySelector and with waitForDocumentElement, both cases fail, but anyways I assume the error comes from earlier.
I am getting an error and I am not sure why. Could you put on the tracks to identify the root cause of the following:
TypeError: Failed to execute 'replaceChild' on 'Node': parameter 1 is not of type 'Node'.
at Object.convert (/Users/lemoustachiste/work/lm-frontend/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/Node.js:573:11)
at HTMLDivElement.replaceChild (/Users/lemoustachiste/work/lm-frontend/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/Node.js:292:31)
at NodeJsDom.replaceNode (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-pal-nodejs/dist/nodejs-dom.js:95:29)
at makeElementIntoAnchor (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-templating/dist/commonjs/aurelia-templating.js:2432:19)
at applyInstructions (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-templating/dist/commonjs/aurelia-templating.js:2479:17)
at ViewFactory.create (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-templating/dist/commonjs/aurelia-templating.js:2707:7)
at TemplatingEngine.enhance (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-templating/dist/commonjs/aurelia-templating.js:5290:24)
at /Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-framework/dist/commonjs/aurelia-framework.js:176:28
at new Promise (<anonymous>)
at Aurelia.enhance (/Users/lemoustachiste/work/lm-frontend/node_modules/aurelia-framework/dist/commonjs/aurelia-framework.js:174:12)
Thanks a lot
I am not a jest user. So I simply used the scaffolded TS jest skeleton app from aurelia-cli (au new jest-skeleton --unattended --select typescript,jest,vscode). And found that to be working.
It seems the you are missing the following configuration in your jest.config.js.
testEnvironment: "node",
After only adding that, the tests started working.
I wonder if someone using the jest addon can share it's Vue Storybook configuration, since I can't seem to make it work. I've tried the global mode:
In Storybook's config.js:
import { withTests } from '#storybook/addon-jest';
import results from '../.jest-test-results.json';
addDecorator(
withTests({
results,
})
);
And inside my Story:
storiesOf('Elements/Tag', module)
.addParameters({ jest: ['ThuleTag'] })
.addDecorator(VueInfoAddon)
.addDecorator(withTests({ results })('ThuleTag'))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
)
I get this error:
TypeError: Object(...)(...).addParameters is not a function
I've also tried the local way:
In my Story:
import { storiesOf } from '#storybook/vue'
import { withNotes } from '#storybook/addon-notes'
import results from '../../../jest-test-results.json'
import { withTests } from '#storybook/addon-jest'
import ThuleTag from '../../components/ui/elements/ThuleTag.vue'
let _notes = `A simple wrapper for the Elements el-tag, that accepts the same <i>type</i> and <i>size</i> props`
let _template = `<thule-tag
size="small"
key="name">Tag Namez
</thule-tag>`
storiesOf('Elements/Tag', module)
.addDecorator(withTests({ results }))
.add('Squared',
withNotes(_notes)(() => ({
components: {ThuleTag},
template: _template,
propsDescription: {
size: 'medium / small / mini',
type: 'success / info/warning / danger'
}
})),
{
jest: ['ThuleTag.test.js'],
}
)
Here I get this error:
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
And the Tests tab is shown with this message:
This story has tests configured, but no file was found
Can someone point me what's messing things up please?
It looks like storybook jest addon is not supported for Vue.js for now
https://github.com/storybooks/storybook/blob/master/ADDONS_SUPPORT.md
Ok, about first error
Error in render: "TypeError: Cannot read property '__esModule' of undefined"
I think that you should check your babel-config, It seems like you forget some presets for your framework.
About second question
This story has tests configured, but no file was found
That problem happens from Jest and storybook/addon-jest want to get with equals api, but they can't. In last versions of Jest, output file structure has options.testResults , but storybook/addon-jest wants options.results & options.results.testResults.
There are two possible solutions:
use appropriate version of Jest and storybook/addon-jest
apply huck in index.js of storybook-jest library, smth like that
if (testFiles && !testFiles.disable) {
//todo: HERE should be your storybook hack
options.results = options.tests.testResults;
options.results.testResults = options.results;
emitAddTests({
kind: kind,
story: story,
testFiles: testFiles,
options: options
});
}
I'm trying out Prisma and React Native right now. Currently I'm trying to upload images to my db with the package _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client). But it's not going so well.
Currently I can select an image with the ImagePicker from Expo. And then I'm trying to do my mutation with the Apollo Client:
await this.props.mutate({
variables: {
name,
description,
price,
image,
},
});
But I get the following error:
Network error: JSON Parse error: Unexpected identifier "POST"
- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError
- node_modules/apollo-client/bundle.umd.js:797:43 in error
And I believe it's from these lines of code:
const image = new ReactNativeFile({
uri: imageUrl,
type: 'image/png',
name: 'i-am-a-name',
});
Which is almost identical from the their example, https://github.com/jaydenseric/apollo-upload-client#react-native.
imageUrl is from my state. And when I console.log image I get the following:
ReactNativeFile {
"name": "i-am-a-name",
"type": "image/png",
"uri": "file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png",
}
So something is popping out. But I can't get any further and I'm hoping I could get some tips from someone.
I also didn't include any code from the backend since I believe the problem lays on the frontend. But if anyone would like to take a look at the backend I can update the question, or you could take a look here: https://github.com/Martinnord/Ecommerce-server/tree/image_uploads.
Thanks a lot for reading! Cheers.
Update
After someone asked after the logic in the server I have decided to past it below:
Product.ts
// import shortid from 'shortid'
import { createWriteStream } from 'fs'
import { getUserId, Context } from '../../utils'
const storeUpload = async ({ stream, filename }): Promise<any> => {
// const path = `images/${shortid.generate()}`
const path = `images/test`
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on('finish', () => resolve({ path }))
.on('error', reject),
)
}
const processUpload = async upload => {
const { stream, filename, mimetype, encoding } = await upload
const { path } = await storeUpload({ stream, filename })
return path
}
export const product = {
async createProduct(parent, { name, description, price, image }, ctx: Context, info) {
// const userId = getUserId(ctx)
const userId = 1;
console.log(image);
const imageUrl = await processUpload(image);
console.log(imageUrl);
return ctx.db.mutation.createProduct(
{
data: {
name,
description,
price,
imageUrl,
seller: {
connect: { id: userId },
},
},
},
info
)
},
}
Solution has been found.
I am a little embarrassed that this was the problem that I faced and I don't know if I should even accept this answer because of awkward I felt when I fixed the issue. But....
There was nothing wrong with my code, but there was a problem with the dependencies versions. I tried to backtrack everything on my app, so I decided to start from the beginning and create a new account. I expected it to work just fine, but I got this error:
Error: Cannot use GraphQLNonNull "User!" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
Then I understand that something (that I didn't think of) was wrong. I checked my dependencies versions and compared them with Graphcool's example, https://github.com/graphcool/graphql-server-example/blob/master/package.json. And I noticed that my dependencies was outdated. So I upgraded them and everything worked! So that was what I had to do. Update my dependencies.
Moral of the story
Always, always check your damn dependencies versions...
Crawling through your code, I have found this repository, which must be the front-end code if I am not mistaken?
As you've mentioned, apollo-upload-server requires some additional set-up and same goes for the front-end part of your project. You can find more about it here.
As far as I know, the problematic part of your code must be the initialisation of the Apollo Client. From my observation, you've put everything Apollo requires inside of src/index folder, but haven't included Apollo Upload Client itself.
I have created a gist from one of my projects which initialises Apollo Upload Client alongside some other things, but I think you'll find yourself out.
https://gist.github.com/maticzav/86892448682f40e0bc9fc4d4a3acd93a
Hope this helps you! 🙂
When I init the application everything is ok, but when I go to any page
like "localhost/" I get this (double: once for the index.html and once for the javascript requested, see bellow) error:
TypeError: undefined is not a function
at hash (myapp\node_modules\express\node_modules\connect\lib\middleware\session.js:341:10)
at myapp\node_modules\express\node_modules\connect\lib\middleware\session.js:324:24
at Promise.module.exports.SessionStore.get (myapp\node_modules\session-mongoose\index.js:85:22)
at Promise.addBack (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:128:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:66:38)
at Promise.complete (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:77:20)
at Query.findOne (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\query.js:1607:15)
at model.Document.init (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\document.js:229:11)
at model.init (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\model.js:196:36)
TypeError: undefined is not a function
at hash (myapp\node_modules\express\node_modules\connect\lib\middleware\session.js:341:10)
at myapp\node_modules\express\node_modules\connect\lib\middleware\session.js:324:24
at Promise.module.exports.SessionStore.get (myapp\node_modules\session-mongoose\index.js:85:22)
at Promise.addBack (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:128:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:66:38)
at Promise.complete (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\promise.js:77:20)
at Query.findOne (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\query.js:1607:15)
at model.Document.init (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\document.js:229:11)
at model.init (myapp\node_modules\session-mongoose\node_modules\mongoose\lib\model.js:196:36)
This is the code I'm using:
var express = require('express');
var app = this.__app = express();
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
store: this.__getSessionStore()
,secret: this.__secretSession
}));
app.post('/rpc', this.__manageRequest.bind(this)); // <-- this method is not even called
app.use("/client", express.static('./client/')); //
// gets the index.html, but files in subfolders (which exists) throws the second error in the double error
app.use("/", express.static('./client/production/build'));
app.listen(this.__appPort, this.__appIp);
How I get the session store:
__getSessionStore: function(){
var express = require('express');
var app = this.__app;
var SessionMongoose = require("session-mongoose")(express);
var mongooseSessionStore = new SessionMongoose({
url: this.__mongodbUrl
,interval: 120000
});
return mongooseSessionStore;
}
Express version: 3.0.0
Mongoose-sessions version: 0.2.0
The undefined method is "crc16" in the hash method: in debug is undefined too
function hash(sess) {
return crc16(JSON.stringify(sess, function(key, val){
if ('cookie' != key) return val;
}));
}
In the crc module, there is a if(window) and window is defined, the problem is that I cannot see where it's defined!
Because of this window, it will not export any of the modules and therefore the function is undefined! I just very hackly removed the if(window) to always export to it's module.
Well, that was a bug in the crc#0.2.0 module (https://github.com/alexgorbatchev/node-crc/pull/10), and the express is requiring that exact version.
What exactly is the problem and how to fix it?
thanks a lot
This only worked the first time, then BUM, same error again...
As the dependencies in the session-mongoose are like this (loosely):
"dependencies": {
"mongoose": ">= 3.0"
},
It downloaded the mongoose 3.5.4! Npm should only have downloaded the 3.0, but I don't know what happened.
Now I deleted that and put the mongoose at the same version as in my app: 3.4.0.
I still don't know what's wrong with the 3.5.4 version or if the problem is not being equal, but here is the fix.
So many time lost because of this... :S
Perhaps edit ./node_modules/express/package.json to tell it to use more recent CRC library.
Change the line:
"crc": "0.2.0",
to
"crc": ">= 0.2.0",
and then run
npm install -d
If that doesn't install an updated crc library, manually delete the folder ./node_modules/express/node_modules/crc and try again.
I don't promise this will work but it is worth a shot!