Best JavaScript code snippet using jest
index.js
Source: index.js
...118 * LICENSE file in the root directory of this source tree.119 */120async function run(maybeArgv, project) {121 try {122 const argv = buildArgv(maybeArgv);123 if (argv.init) {124 await (0, _init().default)();125 return;126 }127 const projects = getProjectListFromCLIArgs(argv, project);128 const {results, globalConfig} = await (0, _core().runCLI)(argv, projects);129 readResultsAndExit(results, globalConfig);130 } catch (error) {131 (0, _jestUtil().clearLine)(process.stderr);132 (0, _jestUtil().clearLine)(process.stdout);133 if (error.stack) {134 console.error(_chalk().default.red(error.stack));135 } else {136 console.error(_chalk().default.red(error));...
cli-parameters.js
Source: cli-parameters.js
...5var processNodeEnv;6/**7 * Builds a valid ARGV array with passed arguments.8 */9function buildArgv(args) {10 var argv = ['/somewhere/node', '/somewhere/selenium-standalone'];11 if (args) {12 argv = argv.concat(args);13 }14 return argv;15}16/**17 * Tests for `selenium-standalone` command parameters parsing.18 */19describe('`selenium-standalone` command parameters', function() {20 // Allow tests to mock `process.platform`21 before(function() {22 this.originalArgv = Object.getOwnPropertyDescriptor(process, 'argv');23 });24 after(function() {25 Object.defineProperty(process, 'argv', this.originalArgv);26 });27 // Ensure that any internal state of the module is clean for each test28 beforeEach(function() {29 if (process.env) {30 processNodeEnv = process.env.NODE_ENV;31 process.env.NODE_ENV = 'test-cli-parameters';32 } else {33 process.env = { NODE_ENV: 'test-cli-parameters' };34 }35 parseCommandAndOptions = require('../bin/selenium-standalone').bind(null, '/path/to/java');36 });37 afterEach(function() {38 delete require.cache[require.resolve('../bin/selenium-standalone')];39 if (processNodeEnv) {40 process.env.NODE_ENV = processNodeEnv;41 } else {42 delete process.env.NODE_ENV;43 }44 });45 describe('action', function() {46 it('is required', function() {47 process.argv = buildArgv();48 expect(parseCommandAndOptions)49 .to.throw(/^No action provided$/);50 });51 it('only accepts valid values', function() {52 process.argv = buildArgv(['test']);53 expect(parseCommandAndOptions).to.throw(/^Invalid action /);54 process.argv = buildArgv(['install']);55 expect(parseCommandAndOptions).to.not.throw();56 process.argv = buildArgv(['start']);57 expect(parseCommandAndOptions).to.not.throw();58 });59 });60 describe('arguments', function() {61 it('are correctly parsed', function() {62 process.argv = buildArgv([63 'install',64 '--test=1',65 '-a', 'ok',66 '-h'67 ]);68 var parsed = parseCommandAndOptions();69 expect(parsed[1].test).to.be.equal(1);70 expect(parsed[1].a).to.be.equal('ok');71 expect(parsed[1].h).to.be.true;72 });73 it('are correctly passed unparsed to selenium when after --', function() {74 process.argv = buildArgv([75 'install',76 '--test=1',77 '--',78 '--test=1',79 '-a', 'ok',80 '-h',81 ]);82 var parsed = parseCommandAndOptions();83 expect(parsed[1].test).to.be.equal(1);84 expect(parsed[1].a).to.be.undefined;85 expect(parsed[1].seleniumArgs).to.deep.equal(['--test=1', '-a', 'ok', '-h']);86 });87 it('takes default values when not specified', function() {88 process.argv = buildArgv(['install']);89 var parsed1 = parseCommandAndOptions('/somewhere');90 var defaultValues = require('../lib/default-config');91 Object.keys(defaultValues).forEach(function(key) {92 expect(parsed1[1][key]).to.deep.equal(defaultValues[key]);93 });94 process.argv = buildArgv(['install', '--drivers.chrome.version=42']);95 var parsed2 = parseCommandAndOptions('/somewhere');96 expect(parsed2[1].drivers.chrome.version).to.be.equal('42');97 expect(parsed2[1].drivers.chrome.baseURL)98 .to.be.equal(defaultValues.drivers.chrome.baseURL);99 });100 it('are correctly parsed from a JSON config file', function() {101 process.argv = buildArgv([102 'install',103 '--config=' + path.join(__dirname, 'fixtures', 'config.valid.json'),104 ]);105 var parsed = parseCommandAndOptions('/somewhere');106 expect(parsed[1].version).to.be.equal('42');107 expect(parsed[1].drivers.ie.version).to.be.equal(42);108 expect(parsed[1].drivers.ie.baseURL).to.be.equal('http://www.google.fr');109 expect(parsed[1].seleniumArgs).to.be.deep.equal([]);110 });111 it('are correctly parsed from a JS module config file', function() {112 process.argv = buildArgv([113 'install',114 '--config=' + path.join(__dirname, 'fixtures', 'config.valid.js'),115 ]);116 var parsed = parseCommandAndOptions('/somewhere');117 expect(parsed[1].version).to.be.equal('42');118 expect(parsed[1].drivers.ie.version).to.be.equal(42);119 expect(parsed[1].drivers.ie.baseURL).to.be.equal('http://www.google.fr');120 expect(parsed[1].seleniumArgs).to.be.deep.equal(['--test=1', '-flag']);121 });122 it('throws if config file is invalid', function() {123 process.argv = buildArgv([124 'install',125 '--config=' + path.join(__dirname, 'fixtures', 'config.invalid.json'),126 ]);127 expect(parseCommandAndOptions).to.throw(/^Error parsing config file :/);128 });129 it('throws if config file is not an object', function() {130 process.argv = buildArgv([131 'install',132 '--config=' + path.join(__dirname, 'fixtures', 'config.invalid.js'),133 ]);134 expect(parseCommandAndOptions).to.throw(/^Error parsing config file : Config file does not exports an object$/);135 });136 it('respects the precedence order : command line > config file > default', function() {137 var defaultValues = require('../lib/default-config');138 process.argv = buildArgv([139 'install',140 '--config=' + path.join(__dirname, 'fixtures', 'config.valid.js'),141 '--drivers.ie.version=43',142 '--',143 '--some=seleniumArgs'144 ]);145 var parsed = parseCommandAndOptions('/somewhere');146 expect(parsed[1].version).to.be.equal('42');147 expect(parsed[1].drivers.ie.arch).to.be.equal(defaultValues.drivers.ie.arch);148 expect(parsed[1].drivers.ie.version).to.be.equal('43');149 expect(parsed[1].seleniumArgs).to.be.deep.equal(['--some=seleniumArgs']);150 });151 });152});
How to mock jQuery .done() so it executes correctly with Jest?
How can I get the arguments called in jest mock function?
jest snapshot breaks with emotion 10 / babel 7 using enzyme
Jest react testing: Check state after delay
How to test HTML content with React testing library
Jest basics: Testing function from component
How to use Jest global Setup and Teardown in a nodeJS project?
jest to continue checking expect() even after error
Remove logging the origin line in Jest
Apollo useQuery() throws Error: ECONNREFUSED when running async test in React Testing Library
You want that .done
or .error
methods are executed but don't want to actually make a request (btw. i don't know about an .error
method just about .fail
) ? Then i would do the following:
Create a global mock for jquery inside a __mocks__
directory at the top level of your working directory:
//__mocks__/jquery.js:
const jQ = jest.requireActual("jquery");
const ajax = jest.fn(() => {
return jQ.Deferred();
});
export const $ = {
...jQ, // We don't want to mock jQuery completely (we might want to alter $.Deferred status)
ajax,
};
export default $;
By putting jquery.js
inside the __mocks__
directory jQuery gets automatically mocked by jest when requested in modules you want to test (well, in this case it gets partially mocked...).
With this setup you can just run your code without making an actual request but normally run .done
and .error
methods and the registered callbacks.
If you don't want to execute the registered callbacks in .done
or .fail
you need to mock them by hand and instead of returning jQ.Deferred()
return a plain javascript object with jest mocks.
Inside a specific test case where you definitly don't want that .done
/.error
calls your registered callback:
// By returning "this" we are able to chain in the way $.ajax("/api", params).done().fail()
const jqXHR = {
done: jest.fn().mockImplementation(function () {
return this;
}),
fail: jest.fn().mockImplementation(function () {
return this;
}),
// some more $.Deferred() methods you want to mock
};
// Overwrite the global $.ajax mock implementation from __mocks__/jquery.js with our custom one
$.ajax.mockImplementation(() => jqXHR)
When you want to simulate success or error inside a specific test case again overwrite the global mock implementation:
For success:
// success
const dfd = $.Deferred();
$.ajax.mockImplementation(() => {
return dfd.resolve("success"); // this is what your done callback will receive as argument
});
For error:
// success
const dfd = $.Deferred();
$.ajax.mockImplementation(() => {
return dfd.reject("error"); // this is what your fail callback will receive as argument
});
Note that it does not make sense to assert that .done
or .fail
was called/not called since both are always called because they register the callbacks you put inside them. Only when $.Deferred
resolves or rejects a specific registered callback gets executed, which you then can test.
For better testability w.r.t unit testing you should factor out the anonymous functions from .done
/.error
. Since JavaScript is weird and not like python (which i like more) you cannot easily mock specific functions inside a module under test. So you would need to put them inside a dedicated module and mock this module completely. Then you could just assert that they were called either in success or error case.
It took me a while to figure out how to correctly handle mocking with jquery so i want to share my experience here. Hope this helps...
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.
ChatGPT broke all Internet records by going viral in the first week of its launch. A million users in 5 days are unprecedented. A conversational AI that can answer natural language-based questions and create poems, write movie scripts, write social media posts, write descriptive essays, and do tons of amazing things. Our first thought when we got access to the platform was how to use this amazing platform to make the lives of web and mobile app testers easier. And most importantly, how we can use ChatGPT for automated testing.
CI/CD has been gaining a lot of attraction & is probably one of the most talked topics for the novices in DevOps. With the availability of CI/CD tools available in the market, configuring and operating a CI/CD pipeline has become a lot easier than what it was 5-6 years ago. Back then there were no containers and the only CI/CD tool that dominated the sphere was Jenkins. Jenkins provided you with a task runner, so you could define your jobs to run either sequentially or in parallel.
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.
Cypress is one of the fast-growing test automation frameworks. As you learn Cypress, you will probably come across the need to integrate your Cypress tests with your CI environment. Jenkins is an open-source Continuous Integration (CI) server that automates your web applications’ build and deploys process. By running your Cypress test suite in Jenkins, you also automate testing as part of the build process.
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!!