Best JavaScript code snippet using jest
build.js
Source: build.js
...69 src: 'app/index.html',70 dest: 'dist/build/index.html'71 },72 {73 src: this.getBuildPath( this.getAmdMinFilename() ),74 dest: 'dist/build/main.js'75 }76 ]77 } )78 },79 setCopyToLatestGruntConfig: function() {80 this.grunt.config.set( 'copy.build_to_latest', {81 files: [82 {83 src: this.getStandalonePath(),84 dest: this.getBuildPath( this.getStandaloneLatestFilename() )85 },86 {87 src: this.getStandaloneMinPath(),88 dest: this.getBuildPath( this.getStandaloneLatestMinFilename() )89 },90 {91 src: this.getBuildPath( this.getAmdMinFilename() ),92 dest: this.getBuildPath( this.getLatestAmdMinFilename() )93 }94 ]95 } )96 },97 getStandaloneFilename: function() {98 return [ Â this.moduleName, this.version, this.standalone, ].join( this.separator ) + this.fileType99 },100 getStandaloneMinFilename: function() {101 return [ Â this.moduleName, this.version, this.standalone, this.min ].join( this.separator ) + this.fileType102 },103 getStandaloneLatestFilename: function() {104 return [ Â this.moduleName, this.latest, this.standalone ].join( this.separator ) + this.fileType105 },106 getAmdMinFilename: function() {107 return [ this.moduleName, this.version, this.amd, this.min ].join( this.separator ) + this.fileType108 },109 getLatestAmdMinFilename: function() {110 return [ Â this.moduleName, this.latest, this.amd, this.min ].join( this.separator ) + this.fileType111 },112 getStandaloneLatestMinFilename: function() {113 return [ Â this.moduleName, this.latest, this.standalone, this.min ].join( this.separator ) + this.fileType114 },115 getBuildPath: function( relativePath ) {116 return [ Â this.basePath, relativePath ].join( '/' )117 },118 getStandalonePath: function() {119 return this.getBuildPath( this.getStandaloneFilename() )120 },121 getStandaloneMinPath: function() {122 return this.getBuildPath( this.getStandaloneMinFilename() )123 },124 log: function() {125 for ( var i in this )126 if ( this.hasOwnProperty( i ) )127 console.log( i, this[ i ] )128 },129 setRequirejsConfig: function() {130 this.mainConfigFile = 'app/main.js'131 this.name = '<%= config.name.raw %>/main'132 this.grunt.config.set( 'requirejs', {133 standalone: { // see https://github.com/jrburke/r.js/blob/master/build/example.build.js134 options: {135 optimizeAllPluginResources: true,136 mainConfigFile: this.mainConfigFile,137 optimize: 'none',138 wrap: true,139 out: this.getStandalonePath(),140 name: this.name,141 include: [ 'bower_components/almond/almond' ]142 }143 },144 amdMin: {145 options: {146 optimizeAllPluginResources: true,147 mainConfigFile: this.mainConfigFile,148 optimize: 'uglify2',149 out: this.getBuildPath( this.getAmdMinFilename() ),150 name: this.name151 }152 },153 standaloneMin: {154 options: {155 optimizeAllPluginResources: true,156 mainConfigFile: this.mainConfigFile,157 optimize: 'uglify2',158 out: this.getStandaloneMinPath(),159 name: this.name,160 include: [ 'bower_components/almond/almond' ]161 }162 }163 } )...
gulpfile.js
Source: gulpfile.js
...87 * @param module88 * @param name89 * @returns {string}90 */91function getBuildPath(module, name) {92 var modulePath = module ? (module + '/') : '';93 return BUILD_PATH + modulePath + (name ? path.build[name] : '');94}95/** build js task */96modulesToBuild.map(function (module) {97 var busterOptions = {98 fileName: getBuildPath(module, '') + '/busters.json',99 length: 5100 };101 gulp.task('js:build:' + module, function () {102 gulp.src(getSrcPath(module, 'js'))103 .pipe(insert.prepend(';'))104 .pipe(sourcemaps.init())105 .pipe(rigger())106 .pipe(concat(RESULT_JS_NAME))107 //.pipe(uglify())108 .pipe(sourcemaps.write())109 .pipe(gulp.dest(getBuildPath(module, 'js')))110 .pipe(bust(busterOptions))111 .pipe(gulp.dest('.'))112 });113 gulp.task('styles:build:' + module, function () {114 gulp.src(getSrcPath(module, 'styles'))115 .pipe(plumber())116 .pipe(sourcemaps.init())117 .pipe(sass())118 .pipe(prefixer())119 // .pipe(cssmin())120 .pipe(sourcemaps.write())121 .pipe(gulp.dest(getBuildPath(module, 'styles')))122 .pipe(bust(busterOptions))123 .pipe(gulp.dest('.'))124 });125 gulp.task('vendorStyles:build:' + module, function () {126 gulp.src(getSrcPath(module, 'vendorStyles'))127 .pipe(rigger())128 .pipe(cssmin())129 .pipe(gulp.dest(getBuildPath(module, 'styles')))130 .pipe(bust(busterOptions))131 .pipe(gulp.dest('.'))132 });133 gulp.task('vendorJs:build:' + module, function () {134 gulp.src(getSrcPath(module, 'vendorJs'))135 .pipe(insert.prepend(';'))136 .pipe(rigger())137 .pipe(uglify())138 .pipe(gulp.dest(getBuildPath(module, 'js')))139 .pipe(bust(busterOptions))140 .pipe(gulp.dest('.'))141 });142 143 gulp.task('images:build:' + module, function () {144 gulp.src(getSrcPath(module, 'images'))145 .pipe(imagemin({146 progressive: true,147 svgoPlugins: [{removeViewBox: false}],148 use: [pngquant()],149 interlaced: true150 }))151 .pipe(gulp.dest(getBuildPath(module, 'images')))152 });153 gulp.task('fonts:build:' + module, function () {154 gulp.src(getSrcPath(module, 'fonts'))155 .pipe(gulp.dest(getBuildPath(module, 'fonts')))156 });157});158gulp.task('watch', function () {159 modulesToBuild.map(function (module) {160 for (var key in path.src) {161 if (path.src.hasOwnProperty(key)) {162 (function (key) {163 var watchPath = getSrcPath(module, key)164 var watchPath2 = getWatchPath(module, key)165 watch([watchPath, watchPath2], function (event, cb) {166 gulp.start(key + ':build:' + module);167 });168 })(key);169 }...
buildconfig.js
Source: buildconfig.js
...28}29function getWebAppPath(mypath) {30 return path.join(basePaths.webAppPath, mypath);31}32function getBuildPath(mypath) {33 if (targetPlatform === 'web') {34 return getWebAppPath(mypath);35 } else {36 return path.join(basePaths.tempPath, targetPlatform, 'rnapp', mypath);37 }38}39function setTargetPlatform(target) {40 switch (target) {41 case 'ios':42 case 'android':43 case 'web':44 case 'windows':45 case 'electron':46 case 'macos':47 case 'tests':48 targetPlatform = target;49 break;50 default:51 targetPlatform = 'web';52 break;53 }54}55function setIsDevEnv(dev) {56 isDevEnv = dev;57}58function getCommonFallback(targetPlatform) {59 switch (targetPlatform) {60 case 'android':61 case 'ios':62 case 'windows':63 case 'macos':64 return 'native';65 case 'web':66 case 'electron':67 case 'tests':68 default:69 return 'web';70 }71}72// Scan the platform-specific modules directory and determines which alias73// to use for the target platform. It searches in the following order:74// 1. modules/<name>/index.<platform>.ts[x]75// 2. modules/<name>/index.<web|native>.ts[x]76// 3. modules/<name>/index.ts[x]77function getModuleAliases(targetPlatform) {78 var aliases = {};79 var fallbackSearchOrder = ['index.' + getCommonFallback(targetPlatform), 'index'];80 var modules = fs.readdirSync('./src/ts/modules/');81 _.each(modules, function (moduleName) {82 var fileNameSearchOrder = [];83 var moduleVariant = 'index.' + targetPlatform;84 _.each(fallbackSearchOrder, function (fallback) {85 var variantPath = './src/ts/modules/' + moduleName + '/' + moduleVariant;86 if (fs.existsSync(variantPath + '.ts') || fs.existsSync(variantPath + '.tsx')) {87 return true;88 }89 moduleVariant = fallback;90 });91 var modulePath = (targetPlatform === 'web' || targetPlatform === 'tests' || targetPlatform === 'electron') ?92 getSourcePath('ts/modules') : './' + getObjPath('modules');93 aliases['modules/' + moduleName] = modulePath + '/' + moduleName + '/' + moduleVariant;94 });95 return aliases;96}97function getConfigInternal() {98 return {99 // Clean100 // --------------------------------------------------------------------- //101 clean: {102 temp: getTempPath('*'),103 web: [104 getBuildPath('fonts/'),105 getBuildPath('images/'),106 getBuildPath('js/')107 ],108 tests: getTempPath('tests/'),109 rnApp: getBuildPath('*')110 },111 // Copy112 // --------------------------------------------------------------------- //113 copy: [114 // fonts115 {116 src: getSourcePath('resources/fonts/**/*.*'),117 dest: getBuildPath('fonts/')118 },119 // images120 {121 src: getSourcePath('resources/images/**/*.*'),122 dest: getBuildPath('images/')123 }124 ],125 // Bundling126 // --------------------------------------------------------------------- //127 bundling: {128 aliases: getModuleAliases(targetPlatform)129 },130 // Build infrastructure131 // --------------------------------------------------------------------- //132 infrastructure: {133 files: [134 './gulpfile.js',135 './buildconfig.js',136 './package.json',137 './webpack.config.js'138 ],139 gulpfile: './gulpfile.js'140 },141 // TypeScript142 // --------------------------------------------------------------------- //143 ts: {144 src: [getSourcePath('ts/**/*.{ts,tsx}')],145 srcRoot: getSourcePath('ts'),146 obj: getObjPath(''),147 config: './tsconfig.json',148 RNDest: getBuildPath('js')149 }150 }151}152module.exports = function getConfig(newTargetPlatform, isDev) {153 setTargetPlatform(newTargetPlatform);154 setIsDevEnv(isDev);155 return getConfigInternal();...
PackageHelper.js
Source: PackageHelper.js
...12function copyFile(source, target) {13 fs.writeFileSync(target, fs.readFileSync(source));14}15var iosSignApp = function(config) {16 var targetPath = getBuildPath(config);17 var signPath = config.output + '/tmp/iReSign.app';18 var sourceSignPath = process.cwd() + '/build/libs/iReSign/bin/iReSign.app'19 //å¤å¶å°ä¸´æ¶ç®å½é20 folder.copy(sourceSignPath, signPath);21 //èµäºæé22 exec('chmod -R 777 ' + signPath);23 //ä¿®æ¹é
ç½®æ件24 copyFile(sourceSignPath + '.plist', signPath + '.plist');25 var tmp = fs.readFileSync(signPath + '.plist');26 tmp = tmp.toString();27 tmp = tmp.replace('[cert]', config.sign.ios.cert);28 tmp = tmp.replace('[provision]', config.sign.ios.provision);29 tmp = tmp.replace('[ipa]', targetPath + config.app.name + '.ipa');30 fs.writeFileSync(signPath + '.plist', tmp);31 //æ§è¡ç¾å32 exec('open -W ' + signPath);33}34var makeIpaIcon = function(config) {35 var icon = config.app.icon;36 var buildPath = getBuildPath(config);37 var command = 'java -jar ' + process.cwd() + '/build/libs/image/ConvertImage.jar ';38 command += '"' + icon + '" ';39 command += '"' + buildPath + '" ';40 command += '64,' + path.basename(config.server.icon);41 try {42 exec(command);43 } catch(e) {44 console.log(e);45 }46}47//å¶ä½plistæ件: æä¾ä¸è½½åè½48var makePlistFile = function(config) {49 var buildPath = getBuildPath(config);50 var ipaPlist = process.cwd() + '/templates/plist/ipa.plist';51 var buf = fs.readFileSync(ipaPlist).toString();52 buf = buf.replace('${title}', config.app.name);53 buf = buf.replace('${version}', config.app.version);54 buf = buf.replace('${package}', config.app.package);55 buf = buf.replace('${display-image}', urlUtil.format(config.server.url + '/' + config.server.icon));56 buf = buf.replace('${software-package}', urlUtil.format(config.server.url + '/' + config.server.ipa));57 fs.writeFileSync(buildPath + config.app.name + '.plist', buf);58}59//æå
appçè·¯å¾60var getBuildPath = function(config) {61 var buildPath = path.join(config.output,'build');62 if (!fs.existsSync(buildPath)) {63 folder.mkdirs(buildPath);64 }65 return buildPath;66}67//æå
androidåºç¨68var androidPackage = function(config) {69 var platformsPath = getTargetPath(config.output, 'android');70 if (!fs.existsSync(platformsPath)) {71 console.log('è·³è¿Androidå¹³å°æå
.');72 return;73 }74 var targetPath = getBuildPath(config);75 var buildPath = path.join(platformsPath,'build','outputs','apk');76 //æç
§é¡ºåºä¼å
æ·è´ç¾åè¿ç77 var apkFileName = ['android-armv7-debug.apk', 'android-armv7-release.apk', 'android-debug.apk', 'android-release.apk'];78 var buildPathFiles = scanFileList.scan(buildPath);79 for ( var i in buildPathFiles ){80 var apkFile = path.join(buildPath , buildPathFiles[i]);81 if (fs.existsSync(apkFile)) {82 var apkBaseName = path.basename(apkFile);83 if ( apkFileName.indexOf(apkBaseName) > -1 ){84 copyFile(apkFile, path.join(targetPath , config.app.name + '.apk'));85 break;86 }87 }88 }89}90//æå
IOSåºç¨91var iosPackage = function(config) {92 var targetPath = getBuildPath(config);93 var appFileName = config.app.name+'.ipa';94 var platformsPath = getTargetPath(config.output, 'ios');95 var buildPath = path.join(platformsPath ,'build','device',appFileName)96 if (!fs.existsSync(buildPath)) {97 console.log('è·³è¿IOSå¹³å°æå
');98 return;99 }100 copyFile(buildPath, path.join(targetPath , appFileName));101}102exports.export = function(config) {103 //èµæºæå
104 console.log('å¼å§æå
åºç¨.');105 try {106 androidPackage(config);107 } catch(e) {108 console.log('æå
androidåºç¨å¤±è´¥:'+e);109 }110 try {111 iosPackage(config);112 } catch(e) {113 console.log('æå
IOSåºç¨å¤±è´¥:'+e);114 }115 console.log('æå
å®æ:' + getBuildPath(config));...
staticFiles.js
Source: staticFiles.js
...19) {20 copyFile(file);21} else if (file.endsWith(".json")) {22 writeFileSync(23 getBuildPath(file),24 minifyJSON(readFileSync(file, { encoding: "utf-8" }))25 );26} else if (file.endsWith(".jpg")) {27 imgHandler(file, ".jpg");28} else if (file.endsWith(".png") && !file.includes("icon")) {29 imgHandler(file, ".png");30}31console.log(`finished handling ${file}`);32function copyFile(file) {33 const buildPath = createDir(file);34 copyFileSync(file, buildPath);35}36function imgHandler(file, ext) {37 const buildPath = createDir(file);38 sharp(file)39 .webp({40 quality: 80,41 })42 .toFile(buildPath.replace(ext, ".webp"))43 .catch((err) => {44 console.error(err);45 });46 // Create Preview Image47 sharp(file)48 .webp({49 quality: 10,50 })51 .toFile(toPreviewImage(file).replace(ext, ".webp"))52 .catch((err) => {53 console.error(err);54 });55}56function getBuildPath(file) {57 return file.replace(`${SOURCE_FOLDER}/`, `${BUILD_FOLDER}/`);58}59function createDir(file) {60 const buildPath = getBuildPath(file);61 const dir = buildPath.split("/").slice(0, -1).join("/");62 mkdirSync(dir, { recursive: true });63 return buildPath;64}65function toPreviewImage(file) {66 const buildPath = getBuildPath(file);67 const dir = buildPath.split("/");68 const base = dir.pop();69 dir.push(base.replace(/(.*)?\./, "$1-preview."));70 return dir.join("/");...
publish.js
Source: publish.js
...15 throw new Error(`Undefined target: ${targetName}`);16 }17 return target;18};19const getBuildPath = function getBuildPath(buildName, config, appPackage) {20 const buildDir = utils.getBuildDir(config);21 const name = utils.getProductName(config, appPackage);22 const buildConfig = utils.getBuildTargetConfig(buildName);23 const build = `${name}-${buildConfig.platform}-${buildConfig.arch}`;24 return path.join(buildDir, build);25};26module.exports = function publish(targetName, buildName, config, appPackage) {27 if (!shell.which('butler')) {28 throw new Error('butler needs to be installed and on the path');29 }30 let command = 'butler push --fix-permissions';31 const version = utils.getBuildVersion(config, appPackage);32 if (version) {33 command = `${command} --userversion=${version}`;34 }35 const target = getTarget(targetName, buildName, config);36 const buildPath = getBuildPath(buildName, config, appPackage);37 command = `${command} "${buildPath}" ${target.project}:${target.channel}`;38 shell.exec(command, { async: true });...
prebuild.js
Source: prebuild.js
2const fs = require("fs");3const APP_DIR = process.cwd();4const BUILD_DIR = path.resolve(APP_DIR, "build");5const PUBLIC_DIR = path.resolve(APP_DIR, "public");6function getBuildPath(name) {7 return path.resolve(BUILD_DIR, name);8}9function getPublicPath(name) {10 return path.resolve(PUBLIC_DIR, name);11}12function emptyDir(dir) {13 if (fs.existsSync(dir)) {14 fs.readdir(dir, (_, files) => {15 files.forEach((item) => {16 if (/_|\.[\w]{1,}/.test(item)) {17 fs.unlinkSync(getBuildPath(item));18 } else {19 fs.rmdirSync(getBuildPath(item), { recursive: true });20 }21 });22 });23 } else {24 fs.mkdirSync(dir);25 }26}27function copyPublic(passList) {28 fs.readdir(PUBLIC_DIR, (_, files) => {29 files.forEach((item) => {30 if (!passList.includes(item)) {31 fs.copyFileSync(getPublicPath(item), getBuildPath(item));32 }33 });34 });35}36emptyDir(BUILD_DIR);...
inject-manifest.js
Source: inject-manifest.js
...6const swSrc = join(__dirname, '..', 'dist', '__layer0__', 'service-worker.js')7injectManifest({8 swSrc,9 swDest: swSrc,10 globDirectory: getBuildPath(),11 globPatterns: ['*.{css,js}'],12 globFollow: true, // follow symlinks13 globStrict: true, // fail the build if anything goes wrong while reading the files14 globIgnores: [`**/*-es5.*.js`],15 dontCacheBustURLsMatching: new RegExp('.+.[a-f0-9]{20}..+'), // Look for a 20 character hex string in the file names. This allows us to avoid using cache busting for Angular files because Angular already takes care of that!16 maximumFileSizeToCacheInBytes: 4 * 1024 * 1024, // 4Mb17}).then(({ count, size }) => {18 console.log(`Generated service worker, which will precache ${count} files (${size} bytes)`)...
How to test if a method returns an array of a class in Jest
How do node_modules packages read config files in the project root?
Jest: how to mock console when it is used by a third-party-library?
ERESOLVE unable to resolve dependency tree while installing a pacakge
Testing arguments with toBeCalledWith() in Jest
Is there assertCountEqual equivalent in javascript unittests jest library?
NodeJS: NOT able to set PERCY_TOKEN via package script with start-server-and-test
Jest: How to consume result of jest.genMockFromModule
How To Reset Manual Mocks In Jest
How to move '__mocks__' folder in Jest to /test?
Since Jest tests are runtime tests, they only have access to runtime information. You're trying to use a type, which is compile-time information. TypeScript should already be doing the type aspect of this for you. (More on that in a moment.)
The fact the tests only have access to runtime information has a couple of ramifications:
If it's valid for getAll
to return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have had Entity
elements in it if it hadn't been empty. All it can tell you is it got an array.
In the non-empty case, you have to check every element of the array to see if it's an Entity
. You've said Entity
is a class, not just a type, so that's possible. I'm not a user of Jest (I should be), but it doesn't seem to have a test specifically for this; it does have toBeTruthy
, though, and we can use every
to tell us if every element is an Entity
:
it('should return an array of Entity class', async () => {
const all = await service.getAll()
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
Beware, though, that all calls to every
on an empty array return true
, so again, that empty array issue raises its head.
If your Jest tests are written in TypeScript, you can improve on that by ensuring TypeScript tests the compile-time type of getAll
's return value:
it('should return an array of Entity class', async () => {
const all: Entity[] = await service.getAll()
// ^^^^^^^^^^
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
TypeScript will complain about that assignment at compile time if it's not valid, and Jest will complain at runtime if it sees an array containing a non-Entity
object.
But jonrsharpe has a good point: This test may not be useful vs. testing for specific values that should be there.
Check out the latest blogs from LambdaTest on this topic:
Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.
Storybook offers a clean-room setting for isolating component testing. No matter how complex a component is, stories make it simple to explore it in all of its permutations. Before we discuss the Storybook testing in any browser, let us try and understand the fundamentals related to the Storybook framework and how it simplifies how we build UI components.
Quality Assurance (QA) is at the point of inflection and it is an exciting time to be in the field of QA as advanced digital technologies are influencing QA practices. As per a press release by Gartner, The encouraging part is that IT and automation will play a major role in transformation as the IT industry will spend close to $3.87 trillion in 2020, up from $3.76 trillion in 2019.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial and Selenium JavaScript Tutorial.
Having a strategy or plan can be the key to unlocking many successes, this is true to most contexts in life whether that be sport, business, education, and much more. The same is true for any company or organisation that delivers software/application solutions to their end users/customers. If you narrow that down even further from Engineering to Agile and then even to Testing or Quality Engineering, then strategy and planning is key at every level.
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!