Getting errors while trying to run stryker - javascript

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?

Related

Next.js (React) - Can't import local typescript file into config file

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.

How to use class when testing with Vue, Cypress and Cucumber?

I am trying to implement something simple: I want my e2e tests run with Cypress and cucumber.
I have an application created with Vue CLI 4.1.1. I added with NPM the package: cypress-cucumber-preprocessor (V1.19.0)
Edit:
After a lot of research and tests, I think I found where the problem comes from, but I don't know how to fix it yet:
The '#vue/cli-plugin-babel/preset' does not seem to be working with
.feature file...
My babel.config.js file is:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
Any idea how I can make cli-plugin-babel working with cucumber cypress?
Original message :
I have a Test.feature file, executing steps defined in test.step.js files.
Here is the content of my test.spec.js
import { When, Then } from 'cypress-cucumber-preprocessor/steps';
import { HomePage } from './pages/home.page';
When(/^I open the Home page$/, () => {
let homePage = new HomePage();
homePage.goTo();
});
Then(/^I see "([^"]*)" in the main heading$/, msg => {
cy.contains('h1', msg)
});
And the content of my PageObject home.page.js:
export class HomePage {
goTo() {
cy.visit("/");
}
}
When I run:
npm run test:e2e
I get the following error:
Oops...we found an error preparing this test file:
tests/e2e/features/Test.feature
The error was:
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:
- A missing file or dependency
- A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.
These errors does not occur when I use:
export function goToHomePage() {
cy.visit("/");
}
You can checkout my project on Github: https://github.com/truar/cloudcmr-v2 (branch master for the passing case, branch pageObject_pattern for the failing case).
I am assuming this is something related to ES6 and cypress... but I clearly don't know what is going on here. Besides, everything I find on the Internet talks about cypress cucumber and Typescript, which I don't use...
What am I missing?
I found the answer. See this PR for more details : https://github.com/cypress-io/cypress/issues/2945
Basically, there is an incompatibility between Babel 7 and Cypress 3. I had to change the babel.config.js file :
module.exports = process.env.CYPRESS_ENV
? {}
: {
presets: ["#vue/cli-plugin-babel/preset"]
};
It is just a workaround, not a real fix. We have to disable babel when running cypress.
Hope will help you !

Creating a custom transform in Jest

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.

Testing React API - Unexpected Token error

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/']
};

Grunt browserify fails when requiring react-bootstrap-typeahead

I'm trying to in include https://www.npmjs.com/package/react-bootstrap-typeahead in my project, but when I run my grunt browserify task, I get a ParseError: Unexpected token error. Full message here:
Running "browserify:dist" (browserify) task
>> /path/to/project/node_modules/react-bootstrap-typeahead/css/Typeahead.css:1
>> .bootstrap-typeahead .dropdown-menu {
>> ^
>> ParseError: Unexpected token
Warning: Error running grunt-browserify. Use --force to continue.
Aborted due to warnings.
The issue being that there is a require('/some/file.css') inside the react-bootstrap-typeahead source js.
Here is my grunt browserify task:
browserify: {
dist: {
cwd: 'build',
options: {
transform : ['browserify-css'],
alias: {
'index' : './dist/index.js',
'root' : './dist/containers/root.js',
'designs' : './dist/components/designs.js',
'addMutationForm' : './dist/components/addMutationForm.js',
'ProteinChecker': './dist/containers/ProteinChecker.js',
'configureStore': './dist/configureStore.js',
'actions' : './dist/actions.js',
'reducers' : './dist/reducers.js',
'utils': './dist/utils.js',
},
require: [
'./node_modules/isomorphic-fetch',
'./node_modules/jquery',
'./node_modules/react',
'./node_modules/react-dom',
'./node_modules/bootstrap',
'./node_modules/redux',
'./node_modules/babel-polyfill',
'./node_modules/redux-logger',
'./node_modules/redux-thunk',
'./node_modules/underscore',
'./node_modules/redux-form',
'./node_modules/react-bootstrap-typeahead'
]
},
src: ['./dist/*.js', './dist/*/*.js'],
dest: './public/build/app.js'
}
}
A few things I came across while attempting to solve the problem:
A similar SO (yet unanswered) question but using webpack, not grunt+browserify so I don't believe applicable:
Using react-bootstrap-typeahead generating CSS errors
And a closed issue on the github page of the react-bootstrap-typeahead project, but doesn't address use through grunt:
https://github.com/ericgio/react-bootstrap-typeahead/issues/2
which suggests using browserify-css transform.
I've tried to get grunt to use this transform by adding transform : ['browserify-css'] in the options field, but that didn't work. I still get the exact same error message.
I tried using browserify with the browserify-css transform on the command line to bundle up just this one library, and then include that bundle, but this leads to yet more errors down the line that I believe have to do with relative imports (and I don't think this is a good solution anyway because if I understand browserify right, it will end up including things like react twice, once for the typeahead bundle that I made on the command line and again for the actual app bundle and then the final js file is HUGE!).
Any ideas on how I can resolve this?
Thanks in advance!
So the solution it turns out was to add
"browserify": {
"transform": ["browserify-css"]
}
to the packages.json of react-bootstrap-typeahead.
It was in the browserify-css docs... (facepalm)

Categories