I'm trying to set up the configuration and mock files for jest to parse/ignore image files in order for the tests to pass. Just about every online resource leads me to the jest docs located: https://jestjs.io/docs/webpack#handling-static-assets
which tell you exactly how to handle the situation. However, not in my case. I've tried both options of creating mock files and using a transformer.
My current jest.config.js:
module.exports = {
projects: [
{
displayName: 'Unit',
testMatch: ["**/?(*.)+(spec|test).[tj]s?(x)"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/", "<rootDir>/cypress/"],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "bower_components", "shared"],
moduleNameMapper: {
"^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js'
},
// transform: {
// "\\.js$": "jest",
// "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/fileTransformer.js"
// //'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
// }
},
{
displayName: 'Pacts',
testMatch: ["**/?(*.)+(pacttest).[tj]s?(x)"],
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/", "<rootDir>/cypress/"],
watchPathIgnorePatterns: ["pact/logs/*", "pact/pacts/*"],
}
],
};
my fileMock.js:
module.exports = 'test-file-stub';
My styleMock.js:
module.exports = {};
My fileTransformer.js:
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
//export default module.exports;
my directory:
I've been bouncing back and forth trying different options in the configurations but they pretty much all lead me to the same two errors, one when I try to use the transformer, and another without. With the transformer commented out, I get 2 errors thrown at the fileMock.js file:
TypeError: Invalid URL: test-file-stub
Failed to parse src "test-file-stub" on next/image
Both of these are referring to the suggested string for the mock. I initially thought that maybe the string was a placeholder for code to actually handle something. But after some reading, my understanding is that it's actually just supposed to be a string there. Perhaps it's a specific string dependent on my environment? And next/image is where I'm importing the image component from.
I'm prioritizing the mocking (please correct me if I'm wrong) because my understand is the mock tells jest to ignore the image file and proceed with the rest of the test while the transformer actually attempts to change the file type from js to jpg or png or whatever filetype the image is. However, I'm trying everything I can. When I try to the run the tests with the transformer portion uncommented I receive an error before any tests are even run stating:
TypeError: Jest: a transformm must export something.
(which is why there is a commented out export default statement.)
This is my first time ever attempting anything like this and I think I've reached a point where I cannot think of anything else to try. If anybody has experienced anything like this please lay some knowledge on me. I'm not sure if I have the mockfiles set up incorrectly or if it's something in the configurations.
Thanks.
I was able to work around this by creating an image URL here:
https://www.base64-image.de/
and replacing the "test-file-stub" string with the generated URL string.
module.exports = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV/TSotUHeyg4pChOogFURFHrUIRKoRaoVUHk0s/hCYNSYuLo+BacPBjserg4qyrg6sgCH6AuLk5KbpIif9LCi1iPDjux7t7j7t3gFAvMc0KjAGaXjFTibiYya6IwVeE0I9ujCAgM8uYlaQkPMfXPXx8vYvxLO9zf44uNWcxwCcSzzDDrBCvE09tVgzO+8QRVpRV4nPiUZMuSPzIdcXlN84FhwWeGTHTqTniCLFYaGOljVnR1IgniaOqplO+kHFZ5bzFWStVWfOe/IXhnL68xHWag0hgAYuQIEJBFRsooYIYrTopFlK0H/fwDzh+iVwKuTbAyDGPMjTIjh/8D353a+Unxt2kcBzoeLHtjyEguAs0arb9fWzbjRPA/wxc6S1/uQ5Mf5Jea2nRI6BnG7i4bmnKHnC5A/Q9GbIpO5KfppDPA+9n9E1ZoPcW6Fx1e2vu4/QBSFNXyRvg4BAYLlD2mse7Q+29/Xum2d8PVXFym6OczU4AAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQflCBkOKh9/wZ+SAAAAGXRFWHRDb21tZW50AENyZWF0ZWQgd2l0aCBHSU1QV4EOFwAAAAxJREFUCNdj+P//PwAF/gL+3MxZ5wAAAABJRU5ErkJggg==';
I have the simplest of scripts in LiveCode attempting to parse a small chunk of JSON using the MergJSON library.
This is doubtless something stupid I'm doing as it's been a long day, but I just can't get the JSON parsed into a LiveCode array:
LC Script in a button called 'Connect'
function JSONToArray pJSON
local tArray,tKeys
repeat for each line tKey in mergJSONDecode(pJSON,"tArray")
put JSONToArray(tArray[tKey]) into tArray[tKey]
end repeat
return tArray
end JSONToArray
on mouseUp
put field "MyJSON" into pJSON
answer JSONToArray()
end mouseUp
My JSON
{
"firstname":"Mary",
"lastname":"Smith",
}
The Error:
Button "Connect": execution error at line n/a (External handler: exception) near "could not decode JSON: unexpected token near end of file"
Suggestions would be most welcome....
Thanks,
Steve
Mark B might have it but the other thing could be that you're not passing the parameter to JSONToArray...
put JSONToArray(pJSON) into tArray
put tArray["firstname"]
{
"firstname":"Mary",
"lastname":"Smith", <---dangling comma
}
I have an XmlElement. I am performing a string comparison on the text it contains. By all accounts, the comparison should pass. Until recently, the code has worked successfully. However, it is now failing.
// caller ....
processRow('my title', atag);
...
function processRow(title, rowtag) {
// rowtag.getText() returns the string 'my title'
if (rowtag.getText() == title) {
// ... this section is never entered
In debug mode, I see two identical String objects being compared. Am I doing something wrong?
It turns out an extra space was present in the xml contents. The difference was not reflected in the variable inspection window; however, the logger log presented the string correctly.
In Drupal 7.14, when i Index my Whole Site, Solr is showing following error:
AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=1938&op=do StatusText: Service unavailable (with message)
ResponseText: EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7539 of /project/path/includes/common.inc).
So when i look into the lines in /includes/common.inc (around lines: 7537):
// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
throw new EntityMalformedException(t('Missing bundle property on entity of type #entity_type.', array('#entity_type' => $entity_type)));
}
What is that chunk of code (in common.inc) is doing actually please?
How can i overcome that error?
Please, try this module https://drupal.org/project/taxonomy_orphanage it will delete all empty bundles.
I have a web service that uses Python's SimpleJSON to serialize JSON, and a javascript/ client that uses Google's Visualization API. When I try to read in the JSON response using Google Data Table's Query method, I am getting a "invalid label" error.
I noticed that Google spreadsheet outputs JSON without quotes around the object keys. I tried reading in JSON without the quotes and that works. I was wondering what was the best way to get SimpleJSON output to be read into Google datable using
query = new google.visualization.Query("http://www.myuri.com/api/").
I could use a regex to remove the quotes, but that seems sloppy. The javascript JSON parsing libraries I've tried won't read in JSON syntax without quotes around the object keys.
Here's some good background reading re: quotes around object keys:
http://simonwillison.net/2006/Oct/11/json/.
Are you certain the Google API is expecting JSON? In my experience Google's APIs tend not to be massively broken in a manner you're describing -- it could be that they're actually expecting a different format that merely resembles JSON.
Further poking around reveals instructions for retrieving data in the format Google expects:
For example, to get the dataSourceUrl
from a Google Spreadsheet, do the
following:
In your spreadsheet, select the range of cells.
Select 'Insert' and then 'Gadget' from the menu.
Open the gadget's menu by clicking on the top-right selector.
Select menu option 'Get data source URL'.
I did this and opened the URL in my browser. The data it was returning was certainly not JSON:
google.visualization.Query.setResponse(
{requestId:'0',status:'ok',signature:'1464883469881501252',
table:{cols: [{id:'A',label:'',type:'t',pattern:''},
{id:'B',label:'',type:'t',pattern:''}],
rows: [[{v:'a'},{v:'h'}],[{v:'b'},{v:'i'}],[{v:'c'},{v:'j'}],[{v:'d'},{v:'k'}],[{v:'e'},{v:'l'}],[{v:'f'},{v:'m'}],[{v:'g'},{v:'n'}]]}});
It looks like the result is intended to be directly executed by the browser. Try modifying your code to do something like this:
# old
return simplejson.dumps ({"requestId": 1, "status": "ok", ...})
# new
json = simplejson.dumps ({"requestId": 1, "status": "ok", ...})
return "google.visualization.Query.setResponse(%r);" % json
The "invalid label" error is usually due to a blind eval() on the JSON string, resulting in property names being mistaken as labels (because they have the same syntax -- "foo:").
eval("{ foo: 42, bar: 43 }"); // Results in invalid label
The quick remedy is to make sure your JSON string has parenthesis enclosing the curly braces:
eval("({ foo: 42, bar: 43 })"); // Works
Try enclosing your JSON string in parenthesis to see if the "invalid label" error goes away.
As it turns out :mod:json would also choke at strings in single quotes. This will sort things out though:
Parse JavaScript object as JSON in python:
solution:
>>> from re import sub
>>> import json
>>> js = "{ a: 'a' }"
>>> json.loads(sub("'", '"', sub('\s(\w+):', r' "\1":', js)))
{u'a': u'a'}
Edit: (edge cases reviewed)
So it was brought up that the suggested solution would not cope with all cases and specifically with something like
e.g. {foo: "a sentence: right here!"} will get changed to {"foo": "a "sentence": right here!"}
– Jason S Apr 12 at 18:03
To resolve that we simply need to ensure that we are in fact working with a key and not simply a colon in a string so we do a little look behind magic to hint at a comma(,) or a curly brace({) presence to ensure we have it proper, like so:
colon in string:
>>> js = "{foo: 'a sentence: right here!'}"
>>> json.loads(sub("'", '"', sub('(?<={|,)\s*(\w+):', r' "\1":', js)))
{u'foo': u'a sentence: right here!'}
Which of course is the same as doing:
>>> js = "{foo: 'a sentence: right here!'}"
>>> json.loads(sub('(?<={|,)\s*(\w+):', r' "\1":', js).replace("'",'"'))
{u'foo': u'a sentence: right here!'}
But then I pointed out that this is not the only flaw because what about quotes:
If we are also concerned about escaped quotes we will have to be slightly more specific as to what constitutes a string. The first quote will follow either a curly brace({) a space(\s) or a colon(:) while the last matching quote will come before either a comma(,) or a closing curly brace(}) then we can consider everything in between as part of the same string, like so:
additional quotes in string:
>>> js = "{foo: 'a sentence: it\'s right here!'}"
>>> json.loads(
... sub("(?<=\s|{|:)'(.*?)'(?=,|})",
... r'"\1"',
... sub('(?<={|,)\s*(\w+):', r' "\1":', js))
... )
{u'foo': u"a sentence: it's right here!"}
Watch this space as more edge cases are revealed and solved. Can you spot another?
Or for something more complex perhaps, a real world example as returned by npm view:
From:
{ name: 'chuck',
description: 'Chuck Norris joke dispenser.',
'dist-tags': { latest: '0.0.3' },
versions: '0.0.3',
maintainers: 'qard ',
time: { '0.0.3': '2011-08-19T22:00:54.744Z' },
author: 'Stephen Belanger ',
repository:
{ type: 'git',
url: 'git://github.com/qard/chuck.git' },
version: '0.0.3',
dependencies: { 'coffee-script': '>= 1.1.1' },
keywords:
[ 'chuck',
'norris',
'jokes',
'funny',
'fun' ],
bin: { chuck: './bin/chuck' },
main: 'index',
engines: { node: '>= 0.4.1 < 0.5.0' },
devDependencies: {},
dist:
{ shasum: '3af700056794400218f99b7da1170a4343f355ec',
tarball: 'http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz' },
scripts: {},
directories: {},
optionalDependencies: {} }
To:
{u'author': u'Stephen Belanger ',
u'bin': {u'chuck': u'./bin/chuck'},
u'dependencies': {u'coffee-script': u'>= 1.1.1'},
u'description': u'Chuck Norris joke dispenser.',
u'devDependencies': {},
u'directories': {},
u'dist': {u'shasum': u'3af700056794400218f99b7da1170a4343f355ec',
u'tarball': u'http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz'},
u'dist-tags': {u'latest': u'0.0.3'},
u'engines': {u'node': u'>= 0.4.1 < 0.5.0'},
u'keywords': [u'chuck', u'norris', u'jokes', u'funny', u'fun'],
u'main': u'index',
u'maintainers': u'qard ',
u'name': u'chuck',
u'optionalDependencies': {},
u'repository': {u'type': u'git', u'url': u'git://github.com/qard/chuck.git'},
u'scripts': {},
u'time': {u'0.0.3': u'2011-08-19T22:00:54.744Z'},
u'version': u'0.0.3',
u'versions': u'0.0.3'}
Works for me =)
nJoy!