Best JavaScript code snippet using ava
resource.js
Source:resource.js
...58 let stripped = _.omit(payload, reservedProperties);59 if (this.schema == null) {60 return stripped;61 }62 await this.runHooks({ record: stripped, schema: this.schema }).before(63 "validate"64 );65 const { errors, data } = await this.schema.validate(stripped, {66 ignoreRequired: isUpdate67 });68 _.extend(data, privateProps);69 await this.runHooks({ record: data, schema: this.schema, errors }).after(70 "validate"71 );72 if (errors.length > 0) {73 throw new Error(400, errors.join("\n"));74 }75 return data;76 }77 // ---- Context78 /**79 * Creates a copy of the resource augmented with a context.80 * Contexts are passed to before and after hooks81 *82 * @param {*} ctx83 * @returns84 * @memberof Resource85 */86 withContext(ctx) {87 let clone = new Resource(this.name, this.schema, this.pocket, ctx);88 _.keys(this.hooks, key => {89 _.each(this.hooks[key], (handlers, method) => {90 clone.hooks[key][method] = handlers.map(_.identity);91 });92 });93 return clone;94 }95 // ---- Methods96 /**97 * Returns a record = require(it's ID);98 *99 * @param {*} id100 * @returns101 * @memberof Resource102 */103 get(id, opts) {104 return this.findOne({ _id: id }, opts);105 }106 /**107 * Returns a single record matching the query108 *109 * @param {*} [query={}]110 * @param {*} [options={}]111 * @returns112 * @memberof Resource113 */114 async findOne(query = {}, options = {}) {115 await this.store.ready();116 let records = await this.find(117 query,118 _.extend({}, options, { pageSize: 1 })119 );120 return records[0] || null;121 }122 findAll(opts = {}) {123 return this.find({}, opts);124 }125 /**126 * Returns a list of records marching the query127 *128 * @param {*} [query={}]129 * @param {*} [opts={}]130 * @returns131 * @memberof Resource132 */133 async find(query = {}, opts = {}) {134 await this.store.ready();135 await this.runHooks({ query, options: opts }).before("find", "read");136 let params = {};137 let paginated = false;138 let page = _.isNumber(opts.page) ? opts.page : 1;139 let pageSize = opts.pageSize;140 if (_.isNumber(pageSize)) {141 paginated = true;142 let idx = page > 0 ? page - 1 : 0; // Pages are 1 indexed143 params.skip = idx * pageSize;144 params.limit = pageSize;145 }146 let records = await this.store.find(this.name, query, params);147 if (paginated) {148 const count = await this.store.count(this.name, query);149 records.meta = {150 page,151 pageSize,152 totalPages: Math.ceil(count / pageSize)153 };154 }155 if (!opts.skipComputation) {156 await this.compute(records);157 }158 await this.runHooks({ records, query, options: opts }).after(159 "find",160 "read"161 );162 return records;163 }164 /**165 * Creates a record = require(the payload);166 *167 * @param {*} payload168 * @param {*} [opts={}]169 * @returns170 * @memberof Resource171 */172 async create(payload, opts = {}) {173 await this.store.ready();174 let userId = opts.userId || (this.context.user && this.context.user.id);175 let data = opts.skipValidation ? payload : await this.validate(payload);176 await this.runHooks({ record: data }).before("create", "save");177 data._id = uniqid();178 data._createdAt = Date.now();179 data._updatedAt = data._createdAt;180 data._attachments = [];181 data._createdBy = userId || null;182 let record = await this.store.insert(this.name, data);183 if (!opts.skipComputation) {184 await this.compute(record);185 }186 await this.runHooks({ record }).after("create", "save");187 return record;188 }189 /**190 * Upddates the record specified by the ID by merging in the payload passed as argument191 *192 * @param {*} id193 * @param {*} payload194 * @param {*} [opts={}]195 * @returns196 * @memberof Resource197 */198 async mergeOne(id, payload, opts = {}) {199 let { skipValidation } = opts;200 let data = payload;201 if (!skipValidation) {202 data = await this.validate(payload, { isUpdate: true });203 }204 return this.updateOne(id, { $set: data });205 }206 /**207 * Update multiple records208 *209 * @param {*} query210 * @param {*} operations211 * @returns212 * @memberof Resource213 */214 async update(query, operations, options = {}) {215 await this.store.ready();216 const opts = _.extend({ multi: true }, options);217 await this.runHooks({ query, operations }).before("update");218 await this.store.each(this.name, query, opts).do(async record => {219 const updatedRecord = modify(record, operations);220 updatedRecord._updatedAt = Date.now();221 await this.runHooks({ oldRecord: record, record: updatedRecord }).before("save");222 await this.store.update(223 this.name,224 { _id: record._id },225 { $set: updatedRecord }226 );227 await this.runHooks({ record: updatedRecord, query, operations }).after("update", "save");228 return updatedRecord;229 });230 }231 /**232 * Upsert multiple records233 *234 * @param {*} query235 * @param {*} payload236 * @returns237 * @memberof Resource238 */239 async upsert(query, payload, options = {}) {240 await this.store.ready();241 const exists = await this.findOne(query);242 if (exists) {243 await this.update(query, { $set: payload }, options);244 }245 await this.create(payload, options);246 }247 /**248 * Upsert multiple records249 *250 * @param {*} query251 * @param {*} payload252 * @returns253 * @memberof Resource254 */255 async upsertOne(query, payload, options = {}) {256 await this.store.ready();257 const record = await this.findOne(query);258 if (record) {259 return this.updateOne(record._id, { $set: payload });260 }261 return this.create(payload, options);262 }263 /**264 * Updates the record specified by the ID with the mongo operations265 *266 * @param {*} id267 * @param {*} operations268 * @returns269 * @memberof Resource270 */271 async updateOne(id, operations) {272 const exists = await this.get(id);273 if (!exists) {274 throw RESOURCE_NOT_FOUND;275 }276 await this.update({ _id: id }, operations, { multi: false });277 return this.get(id);278 }279 /**280 * Deletes a record by it's ID281 *282 * @param {*} id283 * @returns284 * @memberof Resource285 */286 removeOne(id) {287 return this.remove({ _id: id }, { multi: false });288 }289 /**290 * Delete records by query291 *292 * @param {*} id293 * @returns294 * @memberof Resource295 */296 async remove(query, options = { multi: true }) {297 await this.store.ready();298 const multi = !!options.multi;299 await this.runHooks({ query, options }).before("remove");300 let removedCount = await this.store.remove(this.name, query, { multi });301 await this.runHooks({ query, options, removedCount }).after("remove");302 return removedCount;303 }304 /**305 * Dros the entire collection. Only available in test mode306 *307 * @returns308 * @memberof Resource309 */310 async drop() {311 if (env() !== "test") {312 throw "Dropping a database is only allowed in test mode";313 }314 await this.store.ready();315 return this.store.remove(this.name, {}, { multi: true });...
record.js
Source:record.js
...65 });66 if (this.created_at) {67 this.created_at = new Date(this.created_at);68 }69 this.runHooks('afterInitialize', { sync: true });70 }71 async delete() {72 await this.runHooks('beforeDelete');73 await Record.getSession().deleteFile(this.id);74 return this.runHooks('afterDelete');75 }76 isPersisted() {77 return !!this.id;78 }79 runHooks(hookName, options = {}) {80 if (options.sync) {81 this.constructor.hooks[hookName].forEach(hook => hook(this, options));82 }83 else {84 return this.runHooksAsync(hookName, options);85 }86 }87 async runHooksAsync(hookName, options) {88 const hooks = this.constructor.hooks[hookName];89 return hooks.reduce(async (previous, current) => {90 await previous;91 return current(this, options);92 }, Promise.resolve(this));93 }94 attributes() {95 return {96 created_at: this.created_at || null,97 id: this.id || null98 };99 }100 async serialize(payload = this) {101 return payload;102 }103 async save(options = {}) {104 if (!options.skipHooks) {105 await this.runHooks('beforeSave', options);106 }107 const payload = this.attributes();108 payload.id = this.id || generateHash(6);109 payload.created_at = this.created_at || new Date();110 // TODO: Maybe snakecase keys before upload? or camelize?111 const serialized = await this.serialize(payload);112 const content = JSON.stringify(serialized);113 const fileOptions = { encrypt: false, verify: false };114 await Record.getSession().putFile(payload.id, content, fileOptions);115 // FIXME: What about code that checks for isPersisted????116 Object.assign(this, payload);117 if (!options.skipHooks) {118 await this.runHooks('afterSave', options);119 }120 return this;121 }122 toJSON() {123 return this.attributes();124 }125}...
Using AI Code Generation
1const test = require('ava');2test.beforeEach(t => {3 t.context.foo = 'bar';4});5test('foo is bar', t => {6 t.is(t.context.foo, 'bar');7});8test('bar is foo', t => {9 t.is(t.context.bar, 'foo');10});11const test = require('ava');12test.beforeEach(t => {13 t.context.bar = 'foo';14});15test('foo is bar', t => {16 t.is(t.context.foo, 'bar');17});18test('bar is foo', t => {19 t.is(t.context.bar, 'foo');20});21I am trying to use the runHooks method of ava to run the hooks of a test file from another test file. I have two test files test.js and test2.js. I want to run the hooks of test.js in test2.js. I am doing that by importing the test.js file in test2.js and calling the runHooks method of ava. But I am getting an error221: const test = require('ava');232: test.beforeEach(t => {243: t.context.foo = 'bar';254: });266: test('foo is bar', t => {277: t.is(t.context.foo, 'bar');288: });2910: test('bar is foo', t => {3011: t.is(t.context.bar, 'foo');3112: });321: const test = require('ava');332: const test1 = require('./test');344: test.beforeEach(t => {355: t.context.bar = 'foo';366: });378: test('foo is bar', t => {389: t.is(t.context.foo, 'bar');3910: });4012: test('bar is foo', t => {4113: t.is(t.context.bar, 'foo');4214: });4316: test1.runHooks();4418: test('foo is bar', t => {4519: t.is(t.context.foo, 'bar');4620: });4722: test('bar is foo', t => {4823: t.is(t.context.bar, 'foo');4924: });
Using AI Code Generation
1import test from 'ava';2test.beforeEach(t => {3 t.context.data = 'foo';4});5test('test 1', t => {6 t.is(t.context.data, 'foo');7});8test('test 2', t => {9 t.is(t.context.data, 'foo');10});11import test from 'ava';12test.beforeEach(t => {13 t.context.data = 'bar';14});15test('test 3', t => {16 t.is(t.context.data, 'bar');17});18test('test 4', t => {19 t.is(t.context.data, 'bar');20});21import test from 'ava';22test.beforeEach(t => {23 t.context.data = 'foo';24});25test('test 5', t => {26 t.is(t.context.data, 'foo');27});28test('test 6', t => {29 t.is(t.context.data, 'foo');30});31import test from 'ava';32test.beforeEach(t => {33 t.context.data = 'bar';34});35test('test 7', t => {36 t.is(t.context.data, 'bar');37});38test('test 8', t => {39 t.is(t.context.data, 'bar');40});41import test from 'ava';42test.beforeEach(t => {43 t.context.data = 'foo';44});45test('test 9', t => {46 t.is(t.context.data, 'foo');47});48test('test 10', t => {49 t.is(t.context.data, 'foo');50});51import test from 'ava';52test.beforeEach(t => {53 t.context.data = 'bar';54});55test('test 11', t => {56 t.is(t.context.data, 'bar');57});58test('test 12', t => {59 t.is(t.context.data, 'bar');60});61import test from 'ava';62test.beforeEach(t => {63 t.context.data = 'foo';64});65test('test
Using AI Code Generation
1import test from 'ava';2import { test as test2 } from 'ava';3import { test as test3 } from 'ava';4import { test as test4 } from 'ava';5import { test as test5 } from 'ava';6import { test as test6 } from 'ava';7import { test as test7 } from 'ava';8import { test as test8 } from 'ava';9import { test as test9 } from 'ava';10import { test as test10 } from 'ava';11import { test as test11 } from 'ava';12import { test as test12 } from 'ava';13import { test as test13 } from 'ava';14import { test as test14 } from 'ava';15import { test as test15 } from 'ava';16import { test as test16 } from 'ava';17import { test as test17 } from 'ava';18import { test as test18 } from 'ava';19import { test as test19 } from 'ava';20import { test as test20 } from 'ava';21import { test as test21 } from 'ava';22import { test as test22 } from 'ava';23import { test as test23 } from 'ava';24import { test as test24 } from 'ava';25import { test as test25 } from 'ava';26import { test as test26 } from 'ava';27import { test as test27 } from 'ava';28import { test as test28 } from 'ava';29import { test as test29 } from 'ava';30import { test as test30 } from 'ava';31import { test as test31 } from 'ava';32import { test as test32 } from 'ava';33import { test as test33 } from 'ava';34import { test as test34 } from 'ava';35import { test as test35 } from 'ava';36import { test as test36 } from 'ava';37import { test as test37 } from 'ava';38import { test as test38 } from 'ava';39import { test as test39 } from 'ava';40import { test as test40 } from 'ava';41import { test as test41 } from 'ava';42import { test as test42 } from 'ava';43import { test as test43 } from 'ava';44import { test as test44 } from 'ava';45import { test as test45 } from 'ava';46import { test as test46 } from
Using AI Code Generation
1import test from 'ava'2import { runHooks } from 'ava/lib/runner'3 () => {4 console.log('hook 1')5 return Promise.resolve()6 },7 () => {8 console.log('hook 2')9 return Promise.resolve()10 },11 () => {12 console.log('hook 3')13 return Promise.resolve()14 }15test('mytest', async t => {16 await runHooks(hooks)17 t.pass()18})19import test from 'ava'20import { runHooks } from 'ava/lib/runner'21 () => {22 console.log('hook 1')23 return Promise.resolve()24 },25 () => {26 console.log('hook 2')27 return Promise.resolve()28 },29 () => {30 console.log('hook 3')31 return Promise.resolve()32 }33test('mytest', async t => {34 await runHooks(hooks)35 t.pass()36})37import test from 'ava'38import { runHooks } from 'ava/lib/runner'39 () => {40 console.log('hook 1')41 return Promise.resolve()42 },43 () => {44 console.log('hook 2')45 return Promise.resolve()46 },47 () => {48 console.log('hook 3')49 return Promise.resolve()50 }51test('mytest', async t => {52 await runHooks(hooks)53 t.pass()54})55import test from 'ava'56import { runHooks } from 'ava/lib/runner'57 () => {58 console.log('hook 1')59 return Promise.resolve()60 },61 () => {62 console.log('hook 2')63 return Promise.resolve()64 },65 () => {66 console.log('hook
Using AI Code Generation
1const test = require('ava');2const _ = require('lodash');3const hooks = {4};5const testHooks = {6};7test.beforeEach(async t => {8 await t.context.runHooks('beforeEach');9});10test.afterEach(async t => {11 await t.context.runHooks('afterEach');12});13test.cb.beforeEach(t => {14 t.context.runHooks('beforeEach').then(() => {15 t.end();16 });17});18test.cb.afterEach(t => {19 t.context.runHooks('afterEach').then(() => {20 t.end();21 });22});23test.before(async t => {24 await t.context.runHooks('before');25});26test.after(async t => {27 await t.context.runHooks('after');28});29test.cb.before(t => {30 t.context.runHooks('before').then(() => {31 t.end();32 });33});34test.cb.after(t => {35 t.context.runHooks('after').then(() => {36 t.end();37 });38});39test.beforeEach(t => {40 t.context.runHooks('beforeEach');41});42test.afterEach(t => {43 t.context.runHooks('afterEach');44});45test.before(t => {46 t.context.runHooks('before');47});48test.after(t => {49 t.context.runHooks('after');50});51module.exports = {52};53const test = require('./test');54test.testHooks.beforeEach.push(async t => {55 console.log('beforeEach');56});57test.testHooks.afterEach.push(async t => {58 console.log('afterEach');59});60test.test('test', t => {61 t.pass();62});63const test = require('./test');64test.testHooks.beforeEach.push(async t => {65 console.log('beforeEach');66});67test.testHooks.afterEach.push(async t => {68 console.log('afterEach');69});70test.test('test', t => {71 t.pass();72});73const test = require('./test');74test.testHooks.beforeEach.push(async t => {75 console.log('beforeEach');76});
Using AI Code Generation
1import test from 'ava';2import { runHooks } from 'ava/lib/worker/subprocess';3import { EventEmitter } from 'events';4import { promisify } from 'util';5import { execFile } from 'child_process';6test('runHooks', async t => {7 const hooks = {8 };9 const emitter = new EventEmitter();10 const runHooksPromise = promisify(runHooks)(hooks, emitter);11 const result = await runHooksPromise;12 t.true(result);13});14test('execFile', async t => {15 const hooks = {16 };17 const emitter = new EventEmitter();18 const runHooksPromise = promisify(execFile)('echo', ['hello']);19 const result = await runHooksPromise;20 t.true(result);21});22{23 "scripts": {24 },25 "devDependencies": {26 }27}28{29 {30 "targets": {31 }32 }33}
Using AI Code Generation
1test('my test', t => {2 return this.runHooks('before', t).then(() => {3 });4});5module.exports = {6 t => {7 }8};
Using AI Code Generation
1test('test 1', t => {2 t.plan(1);3 return this.runHooks('before', t.context)4 .then(() => {5 t.pass();6 });7});8export default {9 async () => {10 console.log('before hook');11 }12};
Using AI Code Generation
1const test = require('ava');2const { join } = require('path');3const { run, runTests } = require('jest');4const { runHooks } = require('ava/lib/worker/subprocess');5test('test', async t => {6 const options = {7 projects: [join(__dirname, 'jest.config.js')],8 };9 const result = await run([join(__dirname, 'jest.config.js')], options);10 t.is(result.results.success, true);11});12module.exports = {13};
Using AI Code Generation
1import test from 'ava';2import { hooks } from 'ava-patterns';3class TestHooks extends hooks {4 constructor() {5 super();6 }7 async before() {8 }9 async beforeEach() {10 }11 async afterEach() {12 }13 async after() {14 }15}16const testHooks = new TestHooks();17test.before(async () => {18 await testHooks.before();19});20test.after(async () => {21 await testHooks.after();22});23test.beforeEach(async () => {24 await testHooks.beforeEach();25});26test.afterEach(async () => {27 await testHooks.afterEach();28});29test('test 1', t => {30});31test('test 2', t => {32});33test('test 3', t => {34});35test('test 4', t => {36});37test('test 5', t => {38});39test('test 6', t => {40});41test('test 7', t => {42});43test('test 8', t => {44});45test('test 9', t => {46});47test('test 10', t => {48});49test('test 11', t => {50});51test('test 12', t => {52});53test('test 13', t => {54});55test('test 14', t => {56});57test('test 15', t => {58});59test('test 16', t => {60});61test('test 17', t => {62});63test('test 18', t => {64});65test('test 19', t => {66});67test('test 20', t => {68});69test('test 21', t => {70});71test('test 22', t => {72});73test('test 23', t =>
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!