Issue with Karma-Browserify + Karma-Coverage - javascript

I am having issues getting karma-browserify to work with karma-coverage. I have spent a lot of time trying to figure out what is wrong, but I didn't find a solution.
Here is my .js file (the functions don't do anything; they are just mocks to test code coverage):
// src/js/utilities/form-validation.js
let includedInTest = () => true;
let alsoIncludedInTest = () => true;
let notIncludedInTest = () => true;
let alsoNotIncludedInTest = () => true;
export default {
includedInTest,
alsoIncludedInTest
};
This is my test file:
// src/spec/utilities/form-validation.spec.js
import formUtilities from '../../js/utilities/form-validation';
describe('Form validation functions', function () {
it('Should return "true"', function () {
expect(formUtilities.includedInTest()).toBe(true);
});
it('Should return "true"', function () {
expect(formUtilities.alsoIncludedInTest()).toBe(true);
});
});
Finally, this is my karma.conf:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine-jquery', 'jasmine'],
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/jquery-validation/dist/jquery.validate.js',
'src/js/**/*.js',
'src/spec/**/*.spec.js'
],
exclude: [
'src/js/index.js'
],
preprocessors: {
'src/js/**/*.js': ['browserify', 'coverage'],
'src/spec/**/*.spec.js': ['browserify']
},
browserify: {
debug: true,
transform: [
['babelify', { presets: ['es2015'] }]
]
},
reporters: ['mocha', 'coverage'],
mochaReporter: {
colors: {
success: 'green',
info: 'bgBlue',
warning: 'cyan',
error: 'bgRed'
},
symbols: {
success: '√',
info: '#',
warning: '!',
error: 'x'
}
},
coverageReporter: {
instrumenters: { isparta: require('isparta') },
instrumenter: {
'src/**/*.js': 'isparta'
},
dir: 'coverage',
subdir: '.',
reporters: [
{ type: 'html', dir: 'coverage' },
{ type: 'text-summary' }
],
check: {
global: {
statements: 90,
branches: 90,
functions: 90,
lines: 90
},
each: {
statements: 90,
branches: 90,
functions: 90,
lines: 90
}
},
watermarks: {
statements: [50, 75],
functions: [50, 75],
branches: [50, 75],
lines: [50, 75]
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
});
};
This config yields this result:
==== Coverage summary ====
Statements : 100% ( 1/1 )
Branches : 100% ( 2/2 )
Functions : 100% ( 0/0 )
Lines : 100% ( 1/1 )
=============
This is obviously wrong since I have four functions on "form-validation.js", and I am testing two of them. But according to the summary report, there are no functions to be tested.
This line from coverage/index.html reveals only one line is being parsed by karma-coverage:
I also tried 'browserify-istanbul' in the transform array (and removed instrumenters from "coverageReport"):
transform: [
['babelify', { presets: ['es2015'] }],
'browserify-istanbul'
]
But this generates an error:
18 08 2017 15:50:14.617:ERROR [karma]: TypeError: Cannot read property 'start' of undefined
at /Users/gferraz/Sites/OAA-Refactor/node_modules/istanbul/lib/object-utils.js:59:44
at Array.forEach (native)
at Object.addDerivedInfoForFile (/Users/gferraz/Sites/OAA-Refactor/node_modules/istanbul/lib/object-utils.js:58:37)
at Collector.fileCoverageFor (/Users/gferraz/Sites/OAA-Refactor/node_modules/istanbul/lib/collector.js:94:15)
at /Users/gferraz/Sites/OAA-Refactor/node_modules/istanbul/lib/collector.js:108:30
at Array.forEach (native)
at Collector.getFinalCoverage (/Users/gferraz/Sites/OAA-Refactor/node_modules/istanbul/lib/collector.js:107:22)
at checkCoverage (/Users/gferraz/Sites/OAA-Refactor/node_modules/karma-coverage/lib/reporter.js:148:33)
at /Users/gferraz/Sites/OAA-Refactor/node_modules/karma-coverage/lib/reporter.js:257:32
at Array.forEach (native)
at Collection.forEach (/Users/gferraz/Sites/OAA-Refactor/node_modules/karma/lib/browser_collection.js:93:21)
at /Users/gferraz/Sites/OAA-Refactor/node_modules/karma-coverage/lib/reporter.js:247:16
at Array.forEach (native)
at CoverageReporter.onRunComplete (/Users/gferraz/Sites/OAA-Refactor/node_modules/karma-coverage/lib/reporter.js:246:15)
at Server.<anonymous> (/Users/gferraz/Sites/OAA-Refactor/node_modules/karma/lib/events.js:13:22)
at emitTwo (events.js:111:20)
Any suggestions on how to fix the config file?

The config suggested on the correct answer of this post helped me: Karma/Istanbul Code Coverage does not find functions and always returns 100%
Now I am getting an error on the html report ERROR [coverage]: TypeError: Cannot read property 'text' of undefined (meaning the html file I want to generate for the report is not being generated), which seems to be related to istanbul. However, I am getting the right code coverage report on my terminal window:
Strangely enough, the error doesn't happen every time the tests run, so I am able to get the html file just fine sometimes.
Here is the karma.conf that solved the problem addressed on my question:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine-jquery', 'jasmine'],
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/jquery-validation/dist/jquery.validate.js',
'src/js/**/*.js',
'src/spec/**/*.spec.js'
],
exclude: [
'src/js/index.js'
],
preprocessors: {
'src/js/**/*.js': ['browserify'],
'src/spec/**/*.spec.js': ['browserify']
},
browserify: {
debug: true,
extensions: ['.js'],
configure: (bundle) => {
bundle.transform('babelify', { presets: ['es2015'] });
bundle.transform(require('browserify-istanbul')({
ignore: ['**/spec/**']
}));
}
},
reporters: ['mocha', 'coverage'],
coverageReporter: {
dir: 'coverage',
subdir: '.',
reporters: [
{ type: 'html', dir: 'coverage' },
{ type: 'text-summary' }
],
etc...
}
});
};

Related

Optional links when using jest to run tests

I'm trying to run tests on jest. My current project is the technology stack of vue2. x. When I run it, I found that the latest ES6 template supports optional chained syntax, but I don't know how to make jest compatible with it. Is there a solution?
Look like:
xxx.vue
<div
class="popover-arrow"
:style="{ borderBottomColor: $__GAME__?.tips?.bgColor || '' }"></div>
What needs to be supported is ES6 Optional chaining
Here is my configuration:
module.exports = {
coverageDirectory: '.coverage',
testMatch: ['**/__tests__/specs/DetailsUidComponent.spec.js'],
testEnvironment: 'jsdom',
collectCoverageFrom: [
'**/components/DetailsUidComponent/**/**/*.vue',
'**/components/FooterButton/*.vue',
'**/components/PublicShare/*.vue',
'**/components/PublicSkuTemplate/*.vue',
'**/components/MoneyDisplay/*.vue',
'**/Detail/components/Coupon/*.vue',
'**/Detail/components/BottomTips/*.vue',
'**/Detail/components/LordsmobileTipsBottom/*.vue',
'**/Detail/components/SubmitBtn/*.vue',
],
moduleFileExtensions: ['vue', 'js'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
coveragePathIgnorePatterns: ['/node_modules/', 'package.json', 'yarn.lock'],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'#page_detail/(.*)$': '<rootDir>/src/pages/Detail/$1',
},
// verbose: true,
coverageThreshold: {
global: {
branches: 100,
// functions: 80,
// lines: 80,
// statements: 80,
},
// '**/DetailsUidComponent/components/UidComp/*.vue': {
// lines: 100,
// },
},
}
I tried to find the relevant configuration in jest's github, but it was typescript-related, but this is not what I want, I need javascript

Wrong wdio.webapp.conf.js config or chrome driver issue - automated test do not start

For some reason I cannot start my tests written using WebdriverIO together with Mocha + Chai testing frameworks. When I run yarn start command to start them I get such an output with every test:
Execution of 31 spec files started at 2021-07-22T13:36:42.326Z
[0-0] RUNNING in chrome - C:\Users\ADOMAS-PC\Desktop\Automation Projects\driveweb\test\e2e\specs\e2e\cancelDownload.spec.js
[0-0] Error: Failed to create session.
Unable to create session from {
"desiredCapabilities": {
"browserName": "chrome",
"goog:chromeOptions": {
"binary": "C:\u002f\u002fProgram Files\u002f\u002fGoogle\u002f\u002fChrome\u002f\u002fApplication\u002f\u002fchrome.exe",
"prefs": {
"directory_upgrade": true,
"prompt_for_download": false,
"download.default_directory": "C:\\Users\\ADOMAS-PC\\Desktop\\Automation Projects\\driveweb\\test\\data\\downloads",
"download.prompt_for_download": false,
"profile.default_content_setting_values.automatic_downloads": 1
},
"args": [
"--headless",
"--no-sandbox",
"--incognito",
"--disable-gpu",
"--window-size=1600,1000"
]
}
},
"capabilities": {
"firstMatch": [
{
"browserName": "chrome",
"goog:chromeOptions": {
"binary": "C:\u002f\u002fProgram Files\u002f\u002fGoogle\u002f\u002fChrome\u002f\u002fApplication\u002f\u002fchrome.exe",
"prefs": {
"directory_upgrade": true,
"prompt_for_download": false,
"download.default_directory": "C:\\Users\\ADOMAS-PC\\Desktop\\Automation Projects\\driveweb\\test\\data\\downloads",
"download.prompt_for_download": false,
"profile.default_content_setting_values.automatic_downloads": 1
},
"args": [
"--headless",
"--no-sandbox",
"--incognito",
"--disable-gpu",
"--window-size=1600,1000"
]
}
}
]
}
}
Build info: version: '3.141.5', revision: 'd54ebd709a', time: '2018-11-06T11:58:47'
System info: host: 'DESKTOP-AK6OAUH', ip: '10.18.0.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '16.0.1'
Driver info: driver.version: unknown
This is how wdio.webapp.conf.js looks like:
const { createDir, removeDirContents } = require('./test/e2e/helpers/folderHelper');
const { populateData } = require('./test/e2e/helpers/apiHelper');
const { TimelineService } = require('wdio-timeline-reporter/timeline-service');
var mkdirp = require('mkdirp');
const path = require('path');
global.downloadDir = path.join(process.cwd(), 'test/data/downloads');
global.uploadDir = path.join(process.cwd(), 'test/data/uploads');
global.uploadPermDir = path.join(process.cwd(), 'test/data/uploadsPerm');
global.baseUrl = 'https://drive.automation.com/';
exports.config = {
hostname: 'automation-selenium',
port: 4444,
path: '/wd/hub',
specs: [
'./test/e2e/specs/e2e/**/*.spec.js',
'./test/e2e/specs/pages/*.spec.js'
],
maxInstances: 1,
capabilities: [
{
maxInstances: 1,
browserName: 'chrome',
'goog:chromeOptions': {
binary: "C://Program Files//Google//Chrome//Application//chrome.exe",
prefs: {
directory_upgrade: true,
prompt_for_download: false,
'download.default_directory': global.downloadDir,
'download.prompt_for_download': false,
'profile.default_content_setting_values.automatic_downloads': 1
},
args: [
'--headless',
'--no-sandbox',
'--incognito',
'--disable-gpu',
'--window-size=1600,1000']
}
}
],
logLevel: 'debug',
outputDir: './reports/output',
bail: 0,
baseUrl: global.baseUrl,
waitforTimeout: 50000,
connectionRetryTimeout: 60000,
connectionRetryCount: 3,
framework: 'mocha',
mochaOpts: {
ui: 'bdd',
compilers: ['js:#babel/register'],
timeout: 60000,
retries: 1
},
reporters: [
'spec',
[
'allure',
{
outputDir: './reports/allure-results/',
disableWebdriverStepsReporting: true,
disableWebdriverScreenshotsReporting: false
}
]
],
onPrepare: async function(config, capabilities) {
global.baseUrl = config.baseUrl;
createDir(global.downloadDir);
createDir(global.uploadDir);
if (!global.baseUrl.includes('automation.com')) {
await populateData(config.baseUrl);
}
},
afterTest: async function (test, context, { error, result, duration, passed, retries }) {
if (!passed) {
const current_datetime = new Date();
const time = current_datetime.getHours() + "h-" + current_datetime.getMinutes() + "m-" + current_datetime.getSeconds() + "s";
const screenshotDir = path.join(process.cwd(), `screenshots`);
await mkdirp(screenshotDir);
const filename = test.title.replace(/\s+/g, '-');
const screenshotImg = `${screenshotDir}/${time}-${filename}.png`;
browser.saveScreenshot(screenshotImg);
}
},
onComplete: function() {
removeDirContents(global.downloadDir);
removeDirContents(global.uploadDir);
}
};
What I already tried?
Reinstalling chrome browser on my PC.
Installing/reinstalling various libraries like wdio, selenium-standalone and etc.
Run tests from CMD using administrator mode.
Setting binary value to C://Program Files//Google//Chrome//Application//chromedriver.exe
Downgrading node to 12.8.1 version
What else can I try to make them work?
yarn add #wdio/selenium-standalone-service
was a solution to this problem.

npm run build does not work while npm run dev does , NuxtJS

I'm trying to export the dist folder from a nuxtJs project i'v been working on .
everything works fine when i run the project on my local machine with the command
npm run dev
but when i try to run
npm run generate
or
npm run build
the error bellow shows up
ERROR in ./layouts/default.vue 22:83
Module parse failed: Unexpected token (22:83)
File was processed with these loaders:
* ./node_modules/#nuxt/components/dist/loader.js
* ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
| /* nuxt-component-imports */
> installComponents(component, {OurHeader: require('/home/adnane/Desktop/code/adnane's projects/broker-interface-main-5/broker-interface-main/components/OurHeader.vue').default,OurFooter: require('/home/adnane/Desktop/code/adnane's projects/broker-interface-main-5/broker-interface-main/components/OurFooter.vue').default})
|
# ./.nuxt/App.js 27:0-47 29:32-41
# ./.nuxt/index.js
# ./.nuxt/client.js
# multi ./node_modules/#nuxt/components/lib/installComponents.js ./.nuxt/client.js
ERROR in ./pages/plans-packages.vue 23:84
Module parse failed: Unexpected token (23:84)
File was processed with these loaders:
* ./node_modules/#nuxt/components/dist/loader.js
* ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
| /* nuxt-component-imports */
> installComponents(component, {PlansCards: require('/home/adnane/Desktop/code/adnane's projects/broker-interface-main-5/broker-interface-main/components/Plans/PlansCards.vue').default,PlansComparison: require('/home/adnane/Desktop/code/adnane's projects/broker-interface-main-5/broker-interface-main/components/Plans/PlansComparison.vue').default})
|
# ./.nuxt/router.js 107:24-109:3
# ./.nuxt/index.js
# ./.nuxt/client.js
# multi ./node_modules/#nuxt/components/lib/installComponents.js ./.nuxt/client.js
and here's my nuxt.config.js file :
export default {
target: 'static',
loading: false,
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
titleTemplate: "وسيط | %s",
htmlAttrs: {
lang: 'ar',
dir: 'rtl'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
],
script: [
{
src: "https://cdnjs.cloudflare.com/ajax/libs/mixitup/3.3.1/mixitup.min.js",
body: true,
async: true,
defer: true,
},
{
src: "https://unpkg.com/aos#2.3.1/dist/aos.js",
body: true,
},
],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'~/assets/styles/global.scss'
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: '~/plugins/bootstrap.js', mode: 'client' },
{ src: '~/plugins/VueCarousel.js', mode: 'client' },
{ src: '~/plugins/SweetAlert.js', mode: 'client' },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'#nuxtjs/axios',
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
}
}
what may cause the problem ?
I just don't know what happened but since there was a problem in installing the components and loading them , changing the boolean value of the attribute related to The Auto import of the components in nuxt.config.js to false fixed my problem .
// Auto import components: https://go.nuxtjs.dev/config-components
components: false,

Why eslint consider JSX or some react #types undefined, since upgrade typescript-eslint/parser to version 4.0.0

The context is pretty big project built with ReactJs, based on eslint rules, with this eslint configuration
const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1
module.exports = {
extends: [
'eslint:recommended',
'plugin:jsx-a11y/recommended',
'plugin:react/recommended',
'prettier',
'prettier/#typescript-eslint'
],
plugins: [
'react',
'html',
'json',
'prettier',
'import',
'jsx-a11y',
'jest',
'#typescript-eslint',
'cypress'
],
settings: {
'html/indent': '0',
es6: true,
react: {
version: '16.5'
},
propWrapperFunctions: ['forbidExtraProps'],
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.json', '.ts', '.tsx']
},
alias: {
extensions: ['.js', '.jsx', '.json']
}
}
},
env: {
browser: true,
node: true,
es6: true,
jest: true,
'cypress/globals': true
},
globals: {
React: true,
google: true,
mount: true,
mountWithRouter: true,
shallow: true,
shallowWithRouter: true,
context: true,
expect: true,
jsdom: true
},
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'es2020',
ecmaFeatures: {
globalReturn: true,
jsx: true
},
lib: ['ES2020']
},
rules: {
'arrow-parens': ['error', 'as-needed'],
'comma-dangle': ['error', 'never'],
eqeqeq: ['error', 'smart'],
'import/first': 0,
'import/named': 'error',
'import/no-deprecated': process.env.NODE_ENV === 'production' ? 0 : 1,
'import/no-unresolved': ['error', { commonjs: true }],
'jsx-a11y/alt-text': DONT_WARN_CI,
'jsx-a11y/anchor-has-content': DONT_WARN_CI,
'jsx-a11y/anchor-is-valid': DONT_WARN_CI,
'jsx-a11y/click-events-have-key-events': DONT_WARN_CI,
'jsx-a11y/heading-has-content': DONT_WARN_CI,
'jsx-a11y/iframe-has-title': DONT_WARN_CI,
'jsx-a11y/label-has-associated-control': [
'error',
{
controlComponents: ['select']
}
],
'jsx-a11y/label-has-for': [
'error',
{
required: {
some: ['nesting', 'id']
}
}
],
'jsx-a11y/media-has-caption': DONT_WARN_CI,
'jsx-a11y/mouse-events-have-key-events': DONT_WARN_CI,
'jsx-a11y/no-autofocus': DONT_WARN_CI,
'jsx-a11y/no-onchange': 0,
'jsx-a11y/no-noninteractive-element-interactions': DONT_WARN_CI,
'jsx-a11y/no-static-element-interactions': DONT_WARN_CI,
'jsx-a11y/no-noninteractive-tabindex': DONT_WARN_CI,
'jsx-a11y/tabindex-no-positive': DONT_WARN_CI,
'no-console': 'warn',
'no-debugger': 'warn',
'no-mixed-operators': 0,
'no-redeclare': 'off',
'no-restricted-globals': [
'error',
'addEventListener',
'blur',
'close',
'closed',
'confirm',
'defaultStatus',
'defaultstatus',
'event',
'external',
'find',
'focus',
'frameElement',
'frames',
'history',
'innerHeight',
'innerWidth',
'length',
'localStorage',
'location',
'locationbar',
'menubar',
'moveBy',
'moveTo',
'name',
'onblur',
'onerror',
'onfocus',
'onload',
'onresize',
'onunload',
'open',
'opener',
'opera',
'outerHeight',
'outerWidth',
'pageXOffset',
'pageYOffset',
'parent',
'print',
'removeEventListener',
'resizeBy',
'resizeTo',
'screen',
'screenLeft',
'screenTop',
'screenX',
'screenY',
'scroll',
'scrollbars',
'scrollBy',
'scrollTo',
'scrollX',
'scrollY',
'self',
'status',
'statusbar',
'stop',
'toolbar',
'top'
],
'no-restricted-modules': ['error', 'chai'],
'no-unused-vars': [
'error',
{
varsIgnorePattern: '^_',
argsIgnorePattern: '^_'
}
],
'no-var': 'error',
'one-var': ['error', { initialized: 'never' }],
'prefer-const': [
'error',
{
destructuring: 'any'
}
],
'prettier/prettier': 'error',
'react/jsx-curly-brace-presence': [
'error',
{ children: 'ignore', props: 'never' }
],
'react/jsx-no-bind': [
'error',
{
allowArrowFunctions: true
}
],
'react/jsx-no-literals': 1,
'react/jsx-no-target-blank': DONT_WARN_CI,
'react/jsx-no-undef': ['error', { allowGlobals: true }],
'react/no-deprecated': DONT_WARN_CI,
'react/prop-types': 0,
'require-await': 'error',
'space-before-function-paren': 0
},
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
'no-unused-vars': 'off',
'import/no-unresolved': 'off'
}
}
]
}
Since the upgrade of the library "#typescript-eslint/parser": "^4.0.0" from "#typescript-eslint/parser": "^3.10.1" this following command ...
eslint --fix --ext .js,.jsx,.json,.ts,.tsx . && stylelint --fix '**/*.scss'
... brings these following errors
9:45 error 'ScrollBehavior' is not defined no-undef
224:12 error 'KeyboardEventInit' is not defined no-undef
53:5 error 'JSX' is not defined no-undef
I know I could fix them adding to the prop globals also the keys JSX: true or KeyboardEventInit: true but it is not the way I want to go.
Any ideas of what is going on here? Where is the configuration error?
Thanks a lot
I had the same issue when trying to declare variables as of type JSX.Element in typescript. I added "JSX":"readonly" to globals in .eslintrc.json and the problem was gone. In your case it would be:
globals: {
React: true,
google: true,
mount: true,
mountWithRouter: true,
shallow: true,
shallowWithRouter: true,
context: true,
expect: true,
jsdom: true,
JSX: true,
},
From the following link, I got that you actually use several options after JSX. You could use true,false, writable or readonly (but not off).
https://eslint.org/docs/user-guide/configuring
Official answer is here and it says indeed to add them to globals or to disable the no-undef rule because TypeScript already has already its own checks:
I get errors from the no-undef rule about global variables not being defined, even though there are no TypeScript errors
The no-undef lint rule does not use TypeScript to determine the
global variables that exist - instead, it relies upon ESLint's
configuration.
We strongly recommend that you do not use the no-undef lint rule on
TypeScript projects. The checks it provides are already provided by
TypeScript without the need for configuration - TypeScript just does
this significantly better.
As of our v4.0.0 release, this also applies to types. If you use
global types from a 3rd party package (i.e. anything from an #types
package), then you will have to configure ESLint appropriately to
define these global types. For example; the JSX namespace from
#types/react is a global 3rd party type that you must define in your
ESLint config.
Note, that for a mixed project including JavaScript and TypeScript,
the no-undef rule (like any role) can be turned off for TypeScript
files alone by adding an overrides section to .eslintrc.json:
"overrides": [
{
"files": ["*.ts"],
"rules": {
"no-undef": "off"
}
}
]
If you choose to leave on the ESLint no-undef lint rule, you can
manually define the set of allowed globals in your ESLint
config,
and/or you can use one of the pre-defined environment (env)
configurations.
From the typescript-eslint troubleshooting guide:
We strongly recommend that you do not use the no-undef lint rule on TypeScript projects. The checks it provides are already provided by TypeScript without the need for configuration - TypeScript just does this significantly better.
In your .eslintrc.js, turn the rule off for TypeScript files using overrides:
module.exports = {
root: true,
extends: '#react-native-community',
parser: '#typescript-eslint/parser',
plugins: ['#typescript-eslint'],
rules: {
'no-shadow': 'off',
'#typescript-eslint/no-shadow': ['error'],
},
overrides: [
{
files: ['*.ts', '*.tsx'],
rules: {
'no-undef': 'off',
},
},
],
};

Jest only runs single project when specifying two config.js

I have two projects specified in the jest section of my package.json.
"jest": {
"projects": ["<rootDir>/jest.unit.config.js", "<rootDir>/tests/jest.component.config.js"]
}
Whenever I run jest on the command line it only picks up and finds the jest.component.config.js.
I have tried removing jest.component.config.js from the projects list and running jest and it does successfully run the unit test config in that case.
What's the trick to it finding and running both?
//jest.unit.config.js
const jestConfig = require('/common/jest.config');
module.exports = Object.assign(jestConfig, {
displayName: {
color: 'cyan',
name: 'unit-tests'
},
coverageThreshold: {
global: {
branches: 20,
functions: 20,
lines: 20,
statements: 20,
}
}
});
//jest.component.config.js
const jestConfig = require('common/jest.config');
module.exports = Object.assign(jestConfig, {
rootDir: '.',
displayName: {
color: 'yellow',
name: 'component-tests',
},
testMatch: ['./**/*test.ts'],
testEnvironment: './helpers/test-environment.js',
});
//common jest.config.js
module.exports = {
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.{js,jsx,ts,tsx,mjs}",
],
coverageDirectory: "<rootDir>/coverage",
coverageProvider: 'babel',
coverageReporters: ['text', 'html'],
coverageThreshold: {
global: {
branches: 50,
functions: 50,
lines: 50,
statements: 50,
},
},
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'mjs', 'json'],
modulePathIgnorePatterns: [],
prettierPath: "prettier",
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.(js|ts|jsx|tsx|mjs)'],
testPathIgnorePatterns: ['/node_modules/', '/fixtures/', '/__tests__/helpers/', '__mocks__', 'dist', '.yalc'],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
'^.+\\\\.(js|jsx|mjs)$': 'babel-jest',
},
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|ts|jsx|tsx|mjs)$'],
};
Turns out I was overwriting my common jest config with the Object.assign(..) and thus stopping whichever project was first in the list of projects.
To fix this, I was able to make a deep copy of it before using the assign instead.
const commonJest = require('common/jest.config');
const commonJestCopy = Object.assign({}, commonJest)
module.exports = Object.assign(commonJestCopy, {
//...overrides
}

Categories

Resources