I have a basic React app created using create-react-app. I am trying to get started with Pact to do contract testing on my API using the Javascript implementation guide.
I have followed the steps in the above link exactly and have created a basic test which essentially does nothing just so I can get the test to run:
import { Pact } from '#pact-foundation/pact';
it('works', () => {
expect(1).toEqual(1);
});
When running npm run pactTest I get the following error:
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/path/to/file.test.pact.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Pact } from '#pact-foundation/pact';
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
If I change the import line to: const Pact = require('#pact-foundation/pact'); then it works.
The problem is that I can't use require instead of import for anything more than this dummy example, because I use import all over the React project.
There must be something else that im missing, since the Javascript implementation guide uses import { Pact } from '#pact-foundation/pact';
Add below config right after transform object in jest.config.js
'^.+\\.js$': 'babel-jest
Below is the example for your ref
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue'],
transform: {
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
'^.+\\.(js|jsx)?$': 'babel-jest'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: [
'<rootDir>/(tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx))'
],
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
Related
Got the following error while trying to run stryker:
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Details:
C:\....newproject\.stryker-tmp\sandbox9266690\src\App.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){.App {
^
SyntaxError: Unexpected token '.'
..........
Here is my stryker.conf.mjs file:
/** #type {import('#stryker-mutator/api/core').PartialStrykerOptions} */
const config = {
mutate: ["src/components/Home.js"],
_comment:
"This config was generated using 'stryker init'. Please take a look at: https://stryker-mutator.io/docs/stryker-js/configuration/ for more information.",
packageManager: "npm",
reporters: ["html", "clear-text", "progress"],
testRunner: "jest",
testRunner_comment:
"Take a look at https://stryker-mutator.io/docs/stryker-js/jest-runner for information about the jest plugin.",
coverageAnalysis: "off",
};
export default config;
I thought if I specifiy my Home.js file as a mutate than stryker will only run this file, but is seems like it has some problems with other .css files.
Anyone can help me how to solve this issue?
Situation
I would like to run some Database code (mongoDB(mongoose)) on server startup / during builds. Considering next js doesn't have any lifecycle hooks that you can hook into in an easy manner, I was trying to perform the database actions in my webpack (next.config.mjs) configuration. However I ran into some problems with importing local files.
Current setup
This is the code of my current next.config.mjs file. (PS. I have also tried the CommonJS way of requiring the needed files, but that also fails with error meessage "module not found".)
None of the lines that import a local typescript file appear to succeed and I have checked the paths multiple times. They always end up with the error message "ERR_MODULE_NOT_FOUND". Only if a node_module package is imported, it works as expected (the mongoose npm package).
Code
/** #type {import('next').NextConfig} */
const { EmployeesSchema } = await import("./mongodb_schemas/employee_schema");
import { EmployeesSchema } from "./mongodb_schemas/employee_schema";
import "./util/test"
import mongoose from "mongoose";
const nextConfig = {
experimental: {
externalDir: true,
},
reactStrictMode: true,
swcMinify: true,
images: {
domains: ["*", "**", "www.google.com"],
},
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
if (isServer) {
console.log(process.cwd());
}
return config;
},
};
export default nextConfig;
Anyone got a clue to why this might end up happening / have any possible solutions to the problem? I have also tried with a normal JavaScript file instead of a Typescript file, which also didn't work. I have found some similar asked questions on Stack Overflow but which were all left unanswered.
My guess for the reason why this occurs: during the build of the project, so when "npm run dev" is ran, the next.config.mjs is copied to a different location into the file structure, which means that the relative paths aren't correct anymore and thus the files can't be found.
PS. My apologize if the question is unclear / in an unusual format, it is my first post so not used to it.
In cypress migration guide they mention that plugin files are no longer supported. They also mention that you need to use >=v3.10 of code-coverage plugin
I do have correct version installed, and I tried to update cypress.config.ts to:
import { defineConfig } from "cypress";
export default defineConfig({
video: false,
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
require('#cypress/code-coverage/task')(on, config)
return config
},
},
});
but it doesn't work. What's the correct way? I believe I do have instrumenting working (I'm using #cypress/instrument-cra and see coverage object) but I don't see generated coverage files and I don't see a reset coverege step in tests
From your description the only step missing is the support file import.
// cypress/support/e2e.js
import '#cypress/code-coverage/support'
I also have a .babelrc with the following, but I believe you can do without it if just covering e2e tests.
{
"plugins": ["istanbul"]
}
Let me know if that's not it, I will give you step-by-step.
I'm trying to set up env vars on my Svelte app to hide an API key.
I followed the instructions in this article [https://medium.com/dev-cafe/how-to-setup-env-variables-to-your-svelte-js-app-c1579430f032].
Here's the structure of my rollup.config.js
import { config as configDotenv } from 'dotenv';
import replace from '#rollup/plugin-replace';
configDotenv();
export default {
...
plugins: [
replace({
__myapp: JSON.stringify({
env: {
isProd: production,
amplitude_api_key : process.env.amplitude_api_key
}
})
}),
]}
When I try to access the env var by calling: __myapp.env.API_KEY
I get this error: __myapp is not defined
It seems that the nesting is the problem. I was able to get it work using this syntax:
replace({
'process.env.isProd': production,
'process.env.amplitude_api_key': process.env.amplitude_api_key
}),
and then use process.env.isProd in your app. Of course, if you like the __myapp thing, you could use __myapp instead of process on the left side of the replace function in your rollup config.
Even though this thread is solved, I want to point out that your remark "to hide an API key" is invalid because .env on clientside is always parsing right into your sourcecode. So in other words: your api-key is being parsed (and exposed) in the source once you build.
I'm trying to create a custom transform for Jest, but running into a documentation roadblock which has me asking myself if I'm even on the right track.
Problem
I have a Rails project which is serving a Vue JS app. I want to write Jest tests for the JS app. In order to pass config variables from Rails to the app, I'm using ERB to template a small number of .js files. For example:
// in server-routes.js.erb
export default {
reports: '<%= Rails.application.config.relative_url_root %><%= Rails.application.routes.url_helpers.reports_path %>',
...
In my Webpack build for the Vue app, I use rails-erb-loader to preprocess the *.erb files before they get passed to the rest of the build process.
However, when I run my JS tests, Jest doesn't know anything about ERB loaders (reasonably enough). So my goal is to add a custom transform for Jest to convert the ERB files when running npm test.
Approach
I thought I might be able to use rails-erb-loader as a Jest transform:
// package.json
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"moduleDirectories": [
"<rootDir>/node_modules"
],
"transform": {
".*\\.(vue)$": "vue-jest",
"^.+\\.js$": "babel-jest",
"^.+\\.js\\.erb$": "rails-erb-loader"
},
This doesn't work, however, because Jest transforms and Webpack loaders seemingly have different signatures. In particular, Jest expects a process function:
$ npm test
FAIL app/javascript/components/__tests__/dummy.test.js
● Test suite failed to run
TypeError: Jest: a transform must export a `process` function.
> 101 | import ServerRoutes from '../server-routes.js.erb';
| ^
at ScriptTransformer._getTransformer (node_modules/#jest/transform/build/ScriptTransformer.js:291:15)
at ScriptTransformer.transformSource (node_modules/#jest/transform/build/ScriptTransformer.js:353:28)
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:457:40)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
at app/javascript/components/related-media.vue:101:1
at Object.<anonymous> (app/javascript/components/related-media.vue:232:3)
And this is where I get stuck, because I can't see where it's documented what the API and behaviour of a process function should be. In the documentation for the transform config option there's a single not very helpful example, and that's it as far as docs go, unless I've missed something.
I also note that babel-jest has a createTransformer function which sounds like it might be helpful, or at least illuminating, but again I can't find any docs on what it does.
If anyone has pointers on the details of creating custom Jest transforms, or at least some better docs, that would be great! Or, if I'm going about this the wrong way, what should I be doing?
You could look at ts-jest. https://github.com/kulshekhar/ts-jest/blob/master/src/ts-jest-transformer.ts. It is in typescript so is typed
Alternatively find the jest code that initiates the transform process. I don't think it is that difficult to find.
I think the transformer is either created with class constructor or via the factory function createTransformer.
From my understanding for the ts-jest-transformer and jest-erb-transformer it seems you need to export an object with public process or to export createTransformer methods which create a transformer object that have a process method.
a simple code example that runs before ts-jest
transform-example.js
const tsJest = require('ts-jest');
const t = tsJest.createTransformer();
module.exports = {
process(fileContent, filePath, jestConfig) {
const res = t.process(fileContent, filePath, jestConfig)
console.log(filePath);
return res;
}
}
jest.config.js
module.exports = {
transform: {
'^.+\\.tsx?$': ['<rootDir>/transform-example']
}
}
running this would run typescript tests (just like ts-jest) and log all the file paths transformed in the test.