How to use testRequire method in Jest

Best JavaScript code snippet using jest

enter.js

Source:enter.js Github

copy

Full Screen

...90 imgList: this.state.imgList.map((item) => {91 item.status = 'success'92 return item93 }),94 disabled: !this.testRequire()95 })96 });97 }98 testRequire(){99 return !!this.state.username && !!this.state.password && !!this.state.phone && !!this.state.levelChecked100 && !!this.state.levelChecked.id && !!this.state.shopName && !!this.state.shopOwner && !!this.state.image && !!this.state.address101 && !!this.state.referrerChecked.id && !!this.state.dailiChecked.id102 }103 onSubmit = e => {104 // console.log(e)105 this.setState({106 loading: true,107 disabled: true108 })109 Taro.request({110 url: ROOT_URL + 'user/nameExist',111 data: {112 name: this.state.username113 }114 }).then(res => {115 console.log(res);116 console.log(Taro.getStorageSync('user_token'));117 if (res['data']['code'] == 0) {118 if (res['data']['data'] == 0){119 this.props.dispatchENTER({120 user: {121 username: this.state.username,122 password: this.state.password123 },124 shopMessage: {125 username: this.state.shopOwner,126 owner_phone: this.state.phone,127 shoptype_id: this.state.levelChecked.id,128 shopname: this.state.shopName,129 shoppicture: this.state.image,130 shopaddress: this.state.address131 },132 recommendID: this.state.referrerChecked.id,133 positionID: this.state.dailiChecked.id,134 token: Taro.getStorageSync('user_token')135 }).then( () => {136 console.log('test');137 this.setState({138 loading: false,139 disabled: false140 })141 this.setState({142 openModal: true143 })144 }).catch(rej => {145 console.log(rej)146 })147 }else {148 Taro.showToast({149 title: '用户未登录'150 })151 }152 }153 })154 }155 onReset = e => {156 console.log(e)157 }158 handleUsernameChange = e => {159 // console.log(e)160 this.setState({161 username: e,162 disabled: !this.testRequire()163 });164 }165 handlePasswordChange = e => {166 // console.log(e)167 this.setState({168 password: e,169 disabled: !this.testRequire()170 })171 }172 handlePhoneChange = e => {173 // console.log(e)174 this.setState({175 phone: e,176 disabled: !this.testRequire()177 })178 }179 handleShopNameChange = e => {180 // console.log(e)181 this.setState({182 shopName: e,183 disabled: !this.testRequire()184 })185 }186 handleShopOwnerChange = e => {187 // console.log(e)188 this.setState({189 shopOwner: e,190 disabled: !this.testRequire()191 })192 }193 handleAddressChange = e => {194 // console.log(e)195 this.setState({196 address: e,197 disabled: !this.testRequire()198 })199 }200 onLevelChange = e => {201 console.log(e);202 const { typeList } = this.props203 console.log(typeList[e.detail.value])204 this.setState({205 levelChecked: typeList[e.detail.value],206 disabled: !this.testRequire()207 })208 }209 onManagerChange = dailiChecked => {210 // console.log(managerChecked)211 const { dailiList } = this.props212 this.setState({213 dailiChecked: dailiList[dailiChecked.detail.value],214 disabled: !this.testRequire()215 })216 }217 onReferrerChange = referrerChecked => {218 const { recommendList } = this.props219 this.setState({220 referrerChecked: recommendList[referrerChecked.detail.value],221 disabled: !this.testRequire()222 })223 }224 succeedCnfirm = () => {225 this.setState({226 openModal: false227 })228 Taro.navigateBack()229 }230 render () {231 const { recommendList, typeList, dailiList } = this.props;232 const { loading, disabled } = this.state;233 let acl = disabled && !this.testRequire();234 return (235 <View className='index'>236 <AtForm237 onSubmit={this.onSubmit}238 onReset={this.onReset}239 >240 <AtInput241 name='value'242 title='用户名'243 type='text'244 placeholder='作为登录使用'245 value={this.state.username}246 onChange={this.handleUsernameChange}247 />...

Full Screen

Full Screen

start.unit.js

Source:start.unit.js Github

copy

Full Screen

1'use strict';2var should = require('chai').should();3var EventEmitter = require('events').EventEmitter;4var path = require('path');5var sinon = require('sinon');6var proxyquire = require('proxyquire');7var start = require('../../lib/scaffold/start');8describe('#start', function() {9 describe('#checkConfigVersion2', function() {10 var sandbox = sinon.sandbox.create();11 beforeEach(function() {12 sandbox.stub(console, 'warn');13 });14 afterEach(function() {15 sandbox.restore();16 });17 it('will give true with "datadir" at root', function() {18 var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;19 var v2 = checkConfigVersion2({datadir: '/home/user/.cicocore/data', services: []});20 v2.should.equal(true);21 });22 it('will give true with "address" service enabled', function() {23 var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;24 var v2 = checkConfigVersion2({services: ['address']});25 v2.should.equal(true);26 });27 it('will give true with "db" service enabled', function() {28 var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;29 var v2 = checkConfigVersion2({services: ['db']});30 v2.should.equal(true);31 });32 it('will give false without "datadir" at root and "address", "db" services disabled', function() {33 var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;34 var v2 = checkConfigVersion2({services: []});35 v2.should.equal(false);36 });37 });38 describe('#setupServices', function() {39 var cwd = process.cwd();40 var setupServices = proxyquire('../../lib/scaffold/start', {}).setupServices;41 it('will require an internal module', function() {42 function InternalService() {}43 InternalService.dependencies = [];44 InternalService.prototype.start = sinon.stub();45 InternalService.prototype.stop = sinon.stub();46 var expectedPath = path.resolve(__dirname, '../../lib/services/internal');47 var testRequire = function(p) {48 p.should.equal(expectedPath);49 return InternalService;50 };51 var config = {52 services: ['internal'],53 servicesConfig: {54 internal: {55 param: 'value'56 }57 }58 };59 var services = setupServices(testRequire, cwd, config);60 services[0].name.should.equal('internal');61 services[0].config.should.deep.equal({param: 'value'});62 services[0].module.should.equal(InternalService);63 });64 it('will require a local module', function() {65 function LocalService() {}66 LocalService.dependencies = [];67 LocalService.prototype.start = sinon.stub();68 LocalService.prototype.stop = sinon.stub();69 var notfoundPath = path.resolve(__dirname, '../../lib/services/local');70 var testRequire = function(p) {71 if (p === notfoundPath) {72 throw new Error();73 } else if (p === 'local') {74 return LocalService;75 } else if (p === 'local/package.json') {76 return {77 name: 'local'78 };79 }80 };81 var config = {82 services: ['local']83 };84 var services = setupServices(testRequire, cwd, config);85 services[0].name.should.equal('local');86 services[0].module.should.equal(LocalService);87 });88 it('will require a local module with "cicocoreNode" in package.json', function() {89 function LocalService() {}90 LocalService.dependencies = [];91 LocalService.prototype.start = sinon.stub();92 LocalService.prototype.stop = sinon.stub();93 var notfoundPath = path.resolve(__dirname, '../../lib/services/local');94 var testRequire = function(p) {95 if (p === notfoundPath) {96 throw new Error();97 } else if (p === 'local/package.json') {98 return {99 name: 'local',100 cicocoreNode: 'lib/cicocoreNode.js'101 };102 } else if (p === 'local/lib/cicocoreNode.js') {103 return LocalService;104 }105 };106 var config = {107 services: ['local']108 };109 var services = setupServices(testRequire, cwd, config);110 services[0].name.should.equal('local');111 services[0].module.should.equal(LocalService);112 });113 it('will throw error if module is incompatible', function() {114 var internal = {};115 var testRequire = function() {116 return internal;117 };118 var config = {119 services: ['cicod']120 };121 (function() {122 setupServices(testRequire, cwd, config);123 }).should.throw('Could not load service');124 });125 });126 describe('#cleanShutdown', function() {127 it('will call node stop and process exit', function() {128 var log = {129 info: sinon.stub(),130 error: sinon.stub()131 };132 var cleanShutdown = proxyquire('../../lib/scaffold/start', {133 '../': {134 log: log135 }136 }).cleanShutdown;137 var node = {138 stop: sinon.stub().callsArg(0)139 };140 var _process = {141 exit: sinon.stub()142 };143 cleanShutdown(_process, node);144 setImmediate(function() {145 node.stop.callCount.should.equal(1);146 _process.exit.callCount.should.equal(1);147 _process.exit.args[0][0].should.equal(0);148 });149 });150 it('will log error during shutdown and exit with status 1', function() {151 var log = {152 info: sinon.stub(),153 error: sinon.stub()154 };155 var cleanShutdown = proxyquire('../../lib/scaffold/start', {156 '../': {157 log: log158 }159 }).cleanShutdown;160 var node = {161 stop: sinon.stub().callsArgWith(0, new Error('test'))162 };163 var _process = {164 exit: sinon.stub()165 };166 cleanShutdown(_process, node);167 setImmediate(function() {168 node.stop.callCount.should.equal(1);169 log.error.callCount.should.equal(1);170 _process.exit.callCount.should.equal(1);171 _process.exit.args[0][0].should.equal(1);172 });173 });174 });175 describe('#registerExitHandlers', function() {176 var log = {177 info: sinon.stub(),178 error: sinon.stub()179 };180 var registerExitHandlers = proxyquire('../../lib/scaffold/start', {181 '../': {182 log: log183 }184 }).registerExitHandlers;185 it('log, stop and exit with an `uncaughtException`', function(done) {186 var proc = new EventEmitter();187 proc.exit = sinon.stub();188 var node = {189 stop: sinon.stub().callsArg(0)190 };191 registerExitHandlers(proc, node);192 proc.emit('uncaughtException', new Error('test'));193 setImmediate(function() {194 node.stop.callCount.should.equal(1);195 proc.exit.callCount.should.equal(1);196 done();197 });198 });199 it('stop and exit on `SIGINT`', function(done) {200 var proc = new EventEmitter();201 proc.exit = sinon.stub();202 var node = {203 stop: sinon.stub().callsArg(0)204 };205 registerExitHandlers(proc, node);206 proc.emit('SIGINT');207 setImmediate(function() {208 node.stop.callCount.should.equal(1);209 proc.exit.callCount.should.equal(1);210 done();211 });212 });213 });214 describe('#registerExitHandlers', function() {215 var stub;216 var registerExitHandlers = require('../../lib/scaffold/start').registerExitHandlers;217 before(function() {218 stub = sinon.stub(process, 'on');219 });220 after(function() {221 stub.restore();222 });223 it('should setup two listeners on process when registering exit handlers', function() {224 registerExitHandlers(process, {});225 stub.callCount.should.equal(2);226 });227 describe('#exitHandler', function() {228 var sandbox;229 var cleanShutdown;230 var exitHandler;231 var logStub;232 before(function() {233 sandbox = sinon.sandbox.create();234 var start = require('../../lib/scaffold/start');235 var log = require('../../lib').log;236 logStub = sandbox.stub(log, 'error');237 cleanShutdown = sandbox.stub(start, 'cleanShutdown', function() {});238 exitHandler = require('../../lib/scaffold/start').exitHandler;239 });240 after(function() {241 sandbox.restore();242 });243 it('should replace the listener for SIGINT after the first SIGINT is handled', function() {244 var options = { sigint: true };245 var node = {};246 exitHandler(options, process, node);247 cleanShutdown.callCount.should.equal(1);248 exitHandler(options, process, node);249 cleanShutdown.callCount.should.equal(1);250 });251 it('should log all errors and stops the services nonetheless', function() {252 var options = { sigint: true };253 var stop = sinon.stub();254 var node = {255 stop: stop256 };257 exitHandler(options, process, node, new Error('some error'));258 logStub.callCount.should.equal(2);259 stop.callCount.should.equal(1);260 });261 });262 });...

Full Screen

Full Screen

resolve.test.js

Source:resolve.test.js Github

copy

Full Screen

...6 */7'use strict';8const dedent = require('dedent');9let platform;10function testRequire(filename) {11 return () => (platform = require(filename));12}13test('should explicitly resolve filename.<platform>.js', () => {14 expect(testRequire('../test1.android.js')).not.toThrow();15 expect(platform.extension).toBe('android.js');16});17test('should explicitly resolve filename.native.js', () => {18 expect(testRequire('../test1.native.js')).not.toThrow();19 expect(platform.extension).toBe('native.js');20});21test('should explicitly resolve filename.js', () => {22 expect(testRequire('../test1.js')).not.toThrow();23 expect(platform.extension).toBe('js');24});25test('should explicitly resolve filename.json', () => {26 expect(testRequire('../test1.json')).not.toThrow();27 expect(platform.extension).toBe('json');28});29test('should resolve filename.<platform>.js', () => {30 expect(testRequire('../test1')).not.toThrow();31 expect(platform.extension).toBe('android.js');32});33test('should resolve filename.<platform>.js from haste package', () => {34 expect(testRequire('custom-resolve/test1')).not.toThrow();35 expect(platform.extension).toBe('android.js');36});37test('should resolve filename.native.js', () => {38 expect(testRequire('../test2')).not.toThrow();39 expect(platform.extension).toBe('native.js');40});41test('should resolve filename.native.js with moduleNameMapper', () => {42 expect(testRequire('test2mapper')).not.toThrow();43 expect(platform.extension).toBe('native.js');44});45test('should resolve filename.js', () => {46 expect(testRequire('../test3')).not.toThrow();47 expect(platform.extension).toBe('js');48});49test('should resolve filename.json', () => {50 expect(testRequire('../test4')).not.toThrow();51 expect(platform.extension).toBe('json');52});53test('should preserve identity for symlinks', () => {54 expect(require('../../../packages/jest-resolve')).toBe(55 require('jest-resolve'),56 );57});58test('should require resolve haste files correctly', () => {59 // We unmock Test5 (they should already be, but to be sure).60 jest.unmock('Test5');61 // Test5 is a standard module, that has a mock (but it is unmocked here).62 expect(require.resolve('Test5')).toBe(require.resolve('../Test5'));63 expect(require('Test5').key).toBe('real');64 // Test6 only exits as a mock; so even when unmocked, we resolve to the mock....

Full Screen

Full Screen

mergeOptions.js

Source:mergeOptions.js Github

copy

Full Screen

...8 * Смешать переданные настройки с дефолтными настройками9 */10export default function mergeOptions (_options={}) {11 const options = deepMerge( defaults, _options );12 testRequire(options.theme.id, 'Отсутствует id темы!');13 testRequire(options.account.id, 'Отсутствует id аккаунта!');14 testRequire(options.account.token, 'Отсутствует token аккаунта!');15 testRequire(options.account.url, 'Отсутствует url аккаунта!');16 options.account.protocol = (options.account.http) ? 'http://' : 'https://';17 // абсолютный путь корня проекта18 options.theme.root = upath.normalize(path.resolve(options.theme.root));19 // урл без http и /. Например shop-48497.myinsales.ru20 options.account.url = options.account.url.replace(/^http.*:[www]*\/\//g, '').split('/')[0];21 // пермалинк для темы22 options.handle = `${options.account.url.split('.')[0]}-${options.theme.id}`;23 // Ссылка на превью темы24 options.themeUrl = options.account.protocol + options.account.url + '/?theme_preview=' + options.theme.id25 // Настройки для подключения к API26 options.insalesApi = {27 id: options.account.id,28 secret: options.account.token,29 http: options.account.http30 }31 return clone(options);32}33/**34 * Проверить обязательное свойство35 */36function testRequire(value, message) {37 if (!value) throw new Error(message);...

Full Screen

Full Screen

runtime_create_mock_from_module.test.js

Source:runtime_create_mock_from_module.test.js Github

copy

Full Screen

...20 const testRequire = runtime.requireModule.bind(21 runtime,22 runtime.__mockRootPath,23 );24 const module = testRequire('RegularModule');25 const origModuleStateValue = module.getModuleStateValue();26 expect(origModuleStateValue).toBe('default');27 // Generate a mock for a module with side effects28 const mock = module.jest.createMockFromModule('ModuleWithSideEffects');29 // Make sure we get a mock.30 expect(mock.fn()).toBe(undefined);31 expect(module.getModuleStateValue()).toBe(origModuleStateValue);32 });33 it('resolves mapped modules correctly', async () => {34 const runtime = await createRuntime(__filename, {moduleNameMapper});35 const root = runtime.requireModule(runtime.__mockRootPath);36 const mockModule = root.jest.createMockFromModule(37 'module/name/createMockFromModule',38 );39 expect(mockModule.test.mock).toBeTruthy();40 });41 });42 it('creates mock objects in the right environment', async () => {43 const runtime = await createRuntime(__filename);44 const testRequire = runtime.requireModule.bind(45 runtime,46 runtime.__mockRootPath,47 );48 const module = testRequire('RegularModule');49 const mockModule = module.jest.createMockFromModule('RegularModule');50 const testObjectPrototype = Object.getPrototypeOf(module.object);51 const mockObjectPrototype = Object.getPrototypeOf(mockModule.object);52 expect(mockObjectPrototype).toBe(testObjectPrototype);53 });...

Full Screen

Full Screen

48resolve.test.js

Source:48resolve.test.js Github

copy

Full Screen

...5 * LICENSE file in the root directory of this source tree.6 */7'use strict';8let platform;9function testRequire(filename) {10 return () => (platform = require(filename));11}12test('should explicitly resolve filename.<platform>.js', () => {13 expect(testRequire('../test1.android.js')).not.toThrow();14 expect(platform.extension).toBe('android.js');15});16test('should explicitly resolve filename.native.js', () => {17 expect(testRequire('../test1.native.js')).not.toThrow();18 expect(platform.extension).toBe('native.js');19});20test('should explicitly resolve filename.js', () => {21 expect(testRequire('../test1.js')).not.toThrow();22 expect(platform.extension).toBe('js');23});24test('should explicitly resolve filename.json', () => {25 expect(testRequire('../test1.json')).not.toThrow();26 expect(platform.extension).toBe('json');27});28test('should resolve filename.<platform>.js', () => {29 expect(testRequire('../test1')).not.toThrow();30 expect(platform.extension).toBe('android.js');31});32test('should resolve filename.<platform>.js from haste package', () => {33 expect(testRequire('custom-resolve/test1')).not.toThrow();34 expect(platform.extension).toBe('android.js');35});36test('should resolve filename.native.js', () => {37 expect(testRequire('../test2')).not.toThrow();38 expect(platform.extension).toBe('native.js');39});40test('should resolve filename.native.js with moduleNameMapper', () => {41 expect(testRequire('test2mapper')).not.toThrow();42 expect(platform.extension).toBe('native.js');43});44test('should resolve filename.js', () => {45 expect(testRequire('../test3')).not.toThrow();46 expect(platform.extension).toBe('js');47});48test('should resolve filename.json', () => {49 expect(testRequire('../test4')).not.toThrow();50 expect(platform.extension).toBe('json');51});52test('should preserve identity for symlinks', () => {53 expect(require('../../../packages/jest-resolve')).toBe(54 require('jest-resolve')55 );...

Full Screen

Full Screen

resolve-test.js

Source:resolve-test.js Github

copy

Full Screen

...6 * of patent rights can be found in the PATENTS file in the same directory.7 */8'use strict';9let platform;10function testRequire(filename) {11 return () => platform = require(filename);12}13test('should explicitly resolve filename.<platform>.js', () => {14 expect(testRequire('../test1.android.js')).not.toThrow();15 expect(platform.extension).toBe('android.js');16});17test('should explicitly resolve filename.native.js', () => {18 expect(testRequire('../test1.native.js')).not.toThrow();19 expect(platform.extension).toBe('native.js');20});21test('should explicitly resolve filename.js', () => {22 expect(testRequire('../test1.js')).not.toThrow();23 expect(platform.extension).toBe('js');24});25test('should explicitly resolve filename.json', () => {26 expect(testRequire('../test1.json')).not.toThrow();27 expect(platform.extension).toBe('json');28});29test('should resolve filename.<platform>.js', () => {30 expect(testRequire('../test1')).not.toThrow();31 expect(platform.extension).toBe('android.js');32});33test('should resolve filename.native.js', () => {34 expect(testRequire('../test2')).not.toThrow();35 expect(platform.extension).toBe('native.js');36});37test('should resolve filename.js', () => {38 expect(testRequire('../test3')).not.toThrow();39 expect(platform.extension).toBe('js');40});41test('should resolve filename.json', () => {42 expect(testRequire('../test4')).not.toThrow();43 expect(platform.extension).toBe('json');...

Full Screen

Full Screen

allTests.js

Source:allTests.js Github

copy

Full Screen

1'use strict';2const testRequire = require.context('../src', true, /\.spec\.js$/);3console.log(testRequire.keys());...

Full Screen

Full Screen

Jest Testing Tutorial

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.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful