I have a file src/api/__mocks__/api-call.js:
module.exports = jest.fn(
(method, endpointPath, queryParams, data, options = {}) => {
if (method === 'GET') {
return {
data: [],
total: 99,
};
}
}
);
ESLint is complaining that "jest is undefined", yet this doesn't happen in my actual __tests__ folder for some reason.
In my project's .eslintrc.js file, I added this:
env: {
jest: true,
},
and this seems to have fixed it. Is this fine or is there a better way?
Related
I am trying to integrate the next-translate library into my Next app, however I am getting an error when configuring the loadLocaleFrom function
This is what my i18n.js file looks like:
module.exports = {
locales: ["en", "fr", "es", "ru", "ar", "zh", "hi", "sw"],
defaultLocale: "en",
pages: {
"*": ["common"],
"/": ["home"],
},
loadLocaleFrom: async (lang, ns) => {
try {
const m = await import(`./locales/${lang}/${ns}.json`);
return {
...m.default,
};
} catch (error) {
console.log(error);
}
},
};
And my next.config file:
const withPlugins = require("next-compose-plugins");
const withImages = require("next-images");
const nextTranslate = require("next-translate");
module.exports = withPlugins([withImages, nextTranslate], {
reactStrictMode: true,
images: {
disableStaticImages: true,
},
});
package.json version:
next-translate: ^1.5.0
next: 12.1.6
react: 17.0.2
Even though my directory has both, the common.json and the home.json files in the correct folder structure, the loadLocaleFrom function still throws an error that looks like this:
Error: Cannot find module './locales/en/common.json'
at webpackEmptyContext (D:\projects\mk\mk-academy\.next\server\pages\index.js:529:10)
at eval (webpack-internal:///./i18n.js:64:89)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.loadLocaleFrom (webpack-internal:///./i18n.js:63:23)
at async Promise.all (index 0) {
code: 'MODULE_NOT_FOUND'
}
I did try using the appWithI18n hoc in _app.js but that doesn't solve it too. I also did try moving the locales to a different directory under src but that shouldn't make a difference.
The image shows my directory structure
require worked for me instead of import
await require(`./locales/${lang}/${ns}.json`)
To generate the code coverage report for vscode extension, i am using nyc and running those via vscode test runner.
Source : https://code.visualstudio.com/api/working-with-extensions/testing-extension
Project structure:
out
-test
-unit
-testcases.js
-index.js
- runTest.js
``
"test": "rm -rf .nyc_output/ && nyc node ./out/test/runTest.js",
"nyc": {
"extends": "#istanbuljs/nyc-config-typescript",
"require": [
"ts-node/register",
"source-map-support/register"
],
"report-dir": ".",
"reporter": [
"text",
"html",
"lcov"
],
"exclude": ["out/test/**"],
"include": [ "out/**/*.js" ],
"check-coverage": true
},
index.ts file:
import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
const mocha = new Mocha({
ui: 'tdd',
color: true,
timeout: 20000,});
const testsRoot = path.resolve(__dirname, '../unit');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => {
mocha.addFile(path.resolve(testsRoot, f));
});
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
e(err);
}
});
});
}
runTest.ts file:
import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to test runner
// Passed to --extensionTestsPath
//const extensionTestsPath = path.resolve(__dirname, './unit/index-coverage');
const extensionTestsPath = path.resolve(__dirname, './unit/index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
//console.error('Failed to run tests');
process.exit(1);
}
}
main();
I was not able to generate code coverage report.It generates report but without any information.
What i am doing wrong here??
There are couple of ways to do this. I found some valuable information while checking below link:
How do a generate vscode TypeScript extension coverage report
Seems the easiest one is from user frenya. but the other two also gives valuable information.
While trying to upgrade babel to v7 in an existing test setup with Jest and Enzyme, I have encountered a problem where Web API File is empty. Although it responds to methods like myFile.name.
Packages used:
babel => 7.6.4
jest => 24.9.0
babel-jest => 24.9.0
Not really an expert with babel, but this is my config
Babe config
const env = process.env.NODE_ENV;
const isProd = () => env === 'production';
const isDev = () => env === 'development';
const isTest = () => env === 'test';
const babelPresetEnvOptions = () => {
const options = {};
if (isTest()) {
options.targets = { node: 'current' };
} else {
// Disable polyfill transforms
options.useBuiltIns = false;
// Do not transform modules to CommonJS
options.modules = false;
}
if (isProd()) {
options.forceAllTransforms = true;
}
return options;
};
const presets = [
[require.resolve('#babel/preset-env'), babelPresetEnvOptions()],
[require.resolve('#babel/preset-react'), { development: isDev() }],
];
const plugins = [
[require.resolve('#babel/plugin-proposal-decorators'), { legacy: true }],
[require.resolve('#babel/plugin-proposal-class-properties'), { loose: true }],
require.resolve('#babel/plugin-proposal-object-rest-spread'),
require.resolve('#babel/plugin-transform-react-jsx'),
require.resolve('#babel/plugin-transform-runtime'),
];
if (isTest()) {
// Compiles import() to a deferred require()
plugins.push(require.resolve('babel-plugin-dynamic-import-node'));
} else {
// Adds syntax support for import()
plugins.push(require.resolve('#babel/plugin-syntax-dynamic-import'));
}
module.exports = api => {
api.assertVersion('^7.6');
return {
presets,
plugins,
};
};
Jest setup
"jest": {
"rootDir": "./webpack",
"setupFiles": [
"<rootDir>/test/jestsetup.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleNameMapper": {
"^.+\\.(css|scss)$": "identity-obj-proxy"
},
"transform": {
"^.+\\.(js|jsx)?$": "babel-jest"
}
},
Problem:
When I try to initiate a file object
const lastModified = 1511256180536;
const myImageFile = new File([''], 'pixel.gif', { type: 'image/gif', lastModified });
console.log(myImageFile); // Also results in => File {}
console.log(imageFile.name); // return 'pixel.gif'
The test snapshot fails as shown below, which I can't explain why.
- file={
- File {
- Symbol(impl): FileImpl {
- "_buffer": Object {
- "data": Array [],
- "type": "Buffer",
- },
- "isClosed": false,
- "lastModified": 1511256180536,
- "name": "pixel.gif",
- "type": "image/gif",
- Symbol(wrapper): [Circular],
- },
- }
- }
+ file={File {}}
Even a hint on this would be great.
Babel debug
#babel/preset-env: `DEBUG` option
Using targets:
{
"node": "12.11"
}
Using modules transform: auto
Using plugins:
syntax-async-generators { "node":"12.11" }
syntax-object-rest-spread { "node":"12.11" }
syntax-json-strings { "node":"12.11" }
syntax-optional-catch-binding { "node":"12.11" }
transform-modules-commonjs { "node":"12.11" }
proposal-dynamic-import { "node":"12.11" }
Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
I'm having trouble getting my configuration right for this. I have a NextJS setup with next-css and I'm trying to add react-svg-loader to the configuration:
next.config.js:
const withCSS = require("#zeit/next-css");
module.exports = withCSS({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]__[hash:base64:4]"
},
webpack(config, options) {
const { dev, isServer } = options;
config.module.rules.push({
test: /\.svg$/,
use: [
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
});
return config;
}
});
The svgs will still fail to load:
{ Error: (client) ./svgs/pencil.svg 10:9 Module parse failed:
Unexpected token (10:9) You may need an appropriate loader to handle
this file type.
Looks like my config above doesn't work but I can't quite figure out why.
I have just simplified the source file to below, which works fine when I use System.import in a script tag.
import angular from "angular";
angular.element(document).ready(function () {
alert('Hello word');;
});
Below is my config.js
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "typescript",
paths: {
"npm:": "jspm_packages/npm/"
},
map: {
"angular": "npm:angular#1.5.2",
"typescript": "npm:typescript#1.8.9"
}
});
I have a gulp task to build it:
gulp.task('bundle:js', ['clean:js'], function () {
var builder = new Builder();
builder.loadConfig('./config.js').then(function () {
var destination = paths.coreJsDest;
builder.buildStatic(paths.srcRoot + 'js/ng/homepage', destination, {
minify: false,
sourceMaps: false,
runtime: false
});
});
});
But the output file contains the file name rather than JavaScript from the file and its imports:
(["1"], ["1"], function($__System) {
})
(function(factory) {
if (typeof define == 'function' && define.amd)
define(["D:/Projects/etc-etc/assets/js/ng/homepage.js"], factory);
else if (typeof module == 'object' && module.exports && typeof require == 'function')
module.exports = factory(require("D:/Projects/etc-etc/js/ng/homepage.js"));
else
throw new Error("Module must be loaded as AMD or CommonJS");
});
Doh, I just needed to change the baseUrl from "/" to "./".