Best JavaScript code snippet using cypress
uploadTest.js
Source:uploadTest.js
...9const authenticationMiddleware = auth.authenticationMiddleware;10const csvParserBuilder = require('../../server/utils/csvParser');11const createBatchloadService = require('../../server/services/batchloadService');12const dbClientStub = {13 bulkInsert: sandbox.stub().returnsPromise().resolves({}),14 clearStaged: sandbox.stub(),15 clearUpload: sandbox.stub(),16 copyNomisIdsFromMaster: sandbox.stub().returnsPromise().resolves(),17 getStagedPncs: sandbox.stub().returnsPromise().resolves({18 rows: [19 {id: 1, offender_pnc: 'a'},20 {id: 2, offender_pnc: 'b'}21 ]22 }),23 getPending: sandbox.stub().returnsPromise().resolves([]),24 fillNomisId: sandbox.stub().returnsPromise().resolves(),25 getInvalidCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),26 getValidCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),27 getCompleteCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),28 getUploadedCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),29 getDuplicateCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),30 getIncompleteCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),31 getFillRejectedCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),32 getPendingCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),33 getRejectedCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),34 getSentCount: sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]}),35 mergeStageToMaster: sandbox.stub().returnsPromise().resolves(),36 updateWithNomisResult: sandbox.stub().returnsPromise().resolves(),37 resetErrors: sandbox.stub().returnsPromise().resolves()38};39const nomisClient = {40 getNomisIdForPnc: sandbox.stub().returnsPromise().resolves([{offenderNo: 'offenderId'}]),41 postComRelation: sandbox.stub().returnsPromise().resolves()42};43const nomisClientBuilder = sandbox.stub().returns(nomisClient);44const loggerStub = {45 debug: sandbox.stub(),46 info: sandbox.stub(),47 warn: sandbox.stub(),48 error: sandbox.stub()49};50const audit = {51 record: sandbox.stub()52};53const fakeSignInService = {54 signIn: sandbox.stub().returns({token: 'fake-system-token'})55};56const testUser = {57 staffId: 'my-staff-id',58 token: 'my-token',59 roleCode: 'OM'60};61const csvParser = csvParserBuilder(loggerStub, dbClientStub);62const batchloadService = createBatchloadService(nomisClientBuilder, dbClientStub, audit, fakeSignInService);63const app = appSetup(createUploadRoute({64 batchloadService,65 logger: loggerStub,66 dbClient: dbClientStub,67 audit,68 authenticationMiddleware,69 csvParser70}), testUser);71describe('upload routes', () => {72 describe('GET /upload', () => {73 afterEach(() => {74 sandbox.reset();75 dbClientStub.getIncompleteCount = sandbox.stub().returnsPromise().resolves({rows: [{count: 3}]});76 });77 it('should get data and re-display page', () => {78 return request(app)79 .get('/')80 .expect(200)81 .expect(res => {82 expect(dbClientStub.getIncompleteCount).to.be.calledOnce();83 expect(dbClientStub.getPendingCount).to.be.calledOnce();84 expect(dbClientStub.getRejectedCount).to.be.calledOnce();85 });86 });87 it('should redirect to route if error', () => {88 dbClientStub.getIncompleteCount = sandbox.stub().returnsPromise().rejects();89 return request(app)90 .get('/')91 .expect(302)92 .expect(res => {93 expect(res.text).to.include('Redirecting to /?error=undefined');94 });95 });96 });97 describe('POST /upload', () => {98 afterEach(() => {99 sandbox.reset();100 });101 it('should add valid data to staging db and redirect to results', () => {102 return request(app)103 .post('/')104 .attach('datafile', __dirname + '/resources/oneValidRow.csv')105 .expect(302)106 .expect(res => {107 expect(dbClientStub.bulkInsert).to.be.calledOnce();108 expect(res.text).to.include('Redirecting to /');109 });110 });111 it('should throw an error if no file uploaded', () => {112 return request(app)113 .post('/')114 .expect(400);115 });116 it('should throw an error if non csv uploaded', () => {117 return request(app)118 .post('/')119 .attach('datafile', __dirname + '/resources/invalid.txt')120 .expect(400);121 });122 it('should redirect to route if error', () => {123 dbClientStub.clearUpload = sandbox.stub().returnsPromise().rejects(new Error('clearUpload'));124 return request(app)125 .post('/')126 .attach('datafile', __dirname + '/resources/oneValidRow.csv')127 .expect(302)128 .expect(res => {129 expect(res.text).to.include('Redirecting to /?error=Error:%20clearUpload');130 });131 });132 });133 describe('GET /clearUpload', () => {134 afterEach(() => {135 sandbox.reset();136 });137 it('should empty the stage data', () => {138 return request(app)139 .get('/clearUpload')140 .expect(302)141 .expect(res => {142 expect(dbClientStub.clearUpload).to.be.calledOnce();143 });144 });145 it('should redirect to route if error', () => {146 dbClientStub.clearUpload = sandbox.stub().returnsPromise().rejects();147 return request(app)148 .get('/clearUpload')149 .expect(302)150 .expect(res => {151 expect(res.text).to.include('Redirecting to /?error=undefined');152 });153 });154 });155 describe('GET /activityStatus', () => {156 afterEach(() => {157 sandbox.reset();158 dbClientStub.getValidCount.resolves({rows: [{count: 3}]});159 });160 it('should return json object with data', () => {161 return request(app)162 .get('/activityStatus')163 .expect(200)164 .expect(res => {165 const data = JSON.parse(res.text);166 expect(data.invalidCount).to.eql(3);167 expect(data.validCount).to.eql(3);168 expect(data.duplicateCount).to.eql(3);169 expect(data.incompleteCount).to.eql(3);170 expect(data.fillRejectedCount).to.eql(3);171 expect(data.pending).to.eql(3);172 expect(data.rejected).to.eql(3);173 expect(data.sent).to.eql(3);174 expect(data.isFilling).to.eql(false);175 expect(data.isSending).to.eql(false);176 });177 });178 it('should return 500 if fails', () => {179 const error = new Error('error');180 dbClientStub.getValidCount.rejects(error);181 return request(app)182 .get('/activityStatus')183 .expect(500)184 .expect(res => {185 expect(res.text).to.contain(JSON.stringify(error));186 });187 });188 });189 describe('GET /stopFill', () => {190 afterEach(() => {191 sandbox.reset();192 });193 it('should redirect to route', () => {194 return request(app)195 .get('/stopFill')196 .expect(302)197 .expect(res => {198 expect(res.text).to.include('Redirecting to /');199 expect(!batchloadService.isFilling());200 });201 });202 });203 describe('GET /stopSend', () => {204 afterEach(() => {205 sandbox.reset();206 });207 it('should redirect to route', () => {208 return request(app)209 .get('/stopSend')210 .expect(302)211 .expect(res => {212 expect(res.text).to.include('Redirecting to /');213 expect(!batchloadService.isSending());214 });215 });216 });217 describe('GET /merge', () => {218 afterEach(() => {219 sandbox.reset();220 });221 it('should redirect to route and call mergeStageToMaster', () => {222 return request(app)223 .get('/merge')224 .expect(302)225 .expect(res => {226 expect(dbClientStub.mergeStageToMaster).to.be.calledOnce();227 expect(res.text).to.include('Redirecting to /');228 });229 });230 it('should redirect to route if error', () => {231 dbClientStub.mergeStageToMaster = sandbox.stub().returnsPromise().rejects();232 return request(app)233 .get('/merge')234 .expect(302)235 .expect(res => {236 expect(res.text).to.include('Redirecting to /?error=undefined');237 });238 });239 });240 describe('GET /viewIncomplete', () => {241 afterEach(() => {242 sandbox.reset();243 });244 it('should redirect to route', () => {245 dbClientStub.getIncomplete = sandbox.stub().returnsPromise().resolves({246 rows: [247 {248 id: 1, timestamp: '2017-12-21 0:0:0.0',249 offender_nomis: 2, offender_pnc: 3,250 staff_id: 4, staff_first: 5, staff_last: 6,251 rejection: 7252 }253 ]254 });255 return request(app)256 .get('/viewIncomplete')257 .expect(200)258 .expect(res => {259 expect(res.text).to.include('<td>1</td>' +260 '<td>2</td>' +261 '<td>3</td>' +262 '<td>4</td>' +263 '<td>5</td>' +264 '<td>6</td>' +265 '<td>7</td>');266 });267 });268 it('should redirect to route if error', () => {269 dbClientStub.getIncomplete = sandbox.stub().returnsPromise().rejects();270 return request(app)271 .get('/viewIncomplete')272 .expect(302)273 .expect(res => {274 expect(res.text).to.include('Redirecting to /?error=undefined');275 });276 });277 });278 describe('GET /viewErrors', () => {279 afterEach(() => {280 sandbox.reset();281 });282 it('should redirect to route', () => {283 dbClientStub.getRejected = sandbox.stub().returnsPromise().resolves({284 rows: [285 {286 id: 1, timestamp: '2017-12-21 0:0:0.0',287 offender_nomis: 2, offender_pnc: 3,288 staff_id: 4, staff_first: 5, staff_last: 6,289 rejection: 7290 }291 ]292 });293 return request(app)294 .get('/viewErrors')295 .expect(200)296 .expect(res => {297 expect(res.text).to.include('<td>1</td>' +298 '<td>2</td>' +299 '<td>3</td>' +300 '<td>4</td>' +301 '<td>5</td>' +302 '<td>6</td>' +303 '<td>7</td>');304 });305 });306 it('should redirect to route if error', () => {307 dbClientStub.getRejected = sandbox.stub().returnsPromise().rejects();308 return request(app)309 .get('/viewErrors')310 .expect(302)311 .expect(res => {312 expect(res.text).to.include('Redirecting to /?error=undefined');313 });314 });315 });316 describe('GET /fill', () => {317 beforeEach(() => {318 dbClientStub.copyNomisIdsFromMaster.resolves();319 dbClientStub.getStagedPncs.resolves({320 rows: [321 {id: 1, offender_pnc: 'a'},...
create.spec.js
Source:create.spec.js
1/* eslint-disable no-unused-expressions, newline-per-chained-call */2import _ from 'lodash';3import config from 'config';4import { clearDB, prepareDB, jwts } from '../../tests';5require('should-sinon');6const request = require('supertest');7const server = require('../../app');8const axios = require('axios');9const sinon = require('sinon');10// const topicJson = require('../../tests/topic.json');11const username = 'test1';12describe('POST /v4/topics ', () => {13 const apiPath = '/v4/topics';14 const testBody = {15 reference: 'reference',16 referenceId: '1',17 tag: 'tag',18 title: 'title',19 body: 'body',20 };21 const testBody2 = {22 reference: 'notexist',23 referenceId: 'notexist',24 tag: 'tag',25 title: 'not exist',26 body: 'not exist',27 };28 let sandbox;29 beforeEach((done) => {30 sandbox = sinon.sandbox.create();31 prepareDB(done);32 });33 afterEach((done) => {34 sandbox.restore();35 clearDB(done);36 });37 it('should return 403 response without a jwt token', (done) => {38 request(server)39 .post(apiPath)40 .expect(403, done);41 });42 it('should return 403 response with invalid jwt token', (done) => {43 request(server)44 .post(apiPath)45 .set({46 Authorization: 'Bearer wrong',47 })48 .expect(403, done);49 });50 it('should return 400 response without body', (done) => {51 request(server)52 .post(apiPath)53 .set({54 Authorization: `Bearer ${jwts.admin}`,55 })56 .expect(400)57 .end((err) => {58 if (err) {59 return done(err);60 }61 return done();62 });63 });64 Object.keys(testBody).forEach((key) => {65 it(`should return 400 response without ${key} parameter`, (done) => {66 const body = _.cloneDeep(testBody);67 delete body[key];68 request(server)69 .post(apiPath)70 .set({71 Authorization: `Bearer ${jwts.admin}`,72 })73 .send(body)74 .expect(400)75 .end((err, res) => {76 if (err) {77 return done(err);78 }79 res.body.should.have.propertyByPath('result', 'content', 'message')80 .eql(`Validation error: "${key}" is required`);81 return done();82 });83 });84 });85 it('should return 403 response with invalid access', (done) => {86 sandbox.stub(axios, 'get').resolves({87 data: {88 result: {},89 },90 });91 request(server)92 .post(apiPath)93 .set({94 Authorization: `Bearer ${jwts.admin}`,95 })96 .send(testBody)97 .expect(403)98 .end((err) => {99 if (err) {100 return done(err);101 }102 return done();103 });104 });105 it('should return 403 response if error to get referenceLookup endpoint', (done) => {106 sandbox.stub(axios, 'get').rejects({});107 request(server)108 .post(apiPath)109 .set({110 Authorization: `Bearer ${jwts.admin}`,111 })112 .send(testBody)113 .expect(403)114 .end((err) => {115 if (err) {116 return done(err);117 }118 return done();119 });120 });121 it('should return 500 response if error to get user and create discourse user', (done) => {122 const data = {123 result: {124 status: 200,125 content: 'content',126 },127 };128 const stub = sandbox.stub(axios, 'get');129 stub.withArgs(`/users/${username}.json`, sinon.match.any)130 .rejects({});131 stub.withArgs(`${config.memberServiceUrl}/${username}`, sinon.match.any)132 .resolves({133 data,134 });135 stub.resolves({136 data,137 });138 sandbox.stub(axios, 'post').rejects({});139 request(server)140 .post(apiPath)141 .set({142 Authorization: `Bearer ${jwts.admin}`,143 })144 .send(testBody)145 .expect(500)146 .end((err) => {147 if (err) {148 return done(err);149 }150 return done();151 });152 });153 it('should return 403 response if user does not have access to identity', (done) => {154 const stub = sandbox.stub(axios, 'get');155 stub.rejects({});156 request(server)157 .post(apiPath)158 .set({159 Authorization: `Bearer ${jwts.admin}`,160 })161 .send(testBody)162 .expect(403)163 .end((err) => {164 if (err) {165 return done(err);166 }167 return done();168 });169 });170 it.skip('should return 500 response if error to get user and failed to create discourse user', (done) => {171 const data = {172 result: {173 status: 200,174 content: 'content',175 },176 };177 const stub = sandbox.stub(axios, 'get');178 stub.withArgs(`/users/${username}.json`, sinon.match.any)179 .rejects({});180 stub.withArgs(`${config.memberServiceUrl}/${username}`, sinon.match.any)181 .resolves({ data });182 stub.resolves({ data });183 const postStub = sandbox.stub(axios, 'post');184 postStub.onFirstCall().rejects({185 response: {186 status: 422,187 },188 });189 request(server)190 .post(apiPath)191 .set({192 Authorization: `Bearer ${jwts.admin}`,193 })194 .send(testBody)195 .expect(500)196 .end((err) => {197 if (err) {198 return done(err);199 }200 return done();201 });202 });203 it.skip('should return 200 response if error to get user and success to create discourse user', (done) => {204 const data = {205 result: {206 status: 200,207 content: 'content',208 },209 topic_id: 1,210 };211 const stub = sandbox.stub(axios, 'get');212 stub.withArgs(`/users/${username}.json`, sinon.match.any)213 .rejects({});214 stub.withArgs(`${config.memberServiceUrl}/${username}`, sinon.match.any)215 .resolves({216 data,217 });218 stub.resolves({219 data,220 });221 const postStub = sandbox.stub(axios, 'post');222 // postStub.onFirstCall().returnsPromise = postStub.returnsPromise;223 // postStub.onSecondCall().returnsPromise = postStub.returnsPromise;224 postStub.onFirstCall().rejects({225 response: {226 status: 403,227 },228 });229 postStub.onSecondCall().resolves({230 data: {231 success: true,232 },233 });234 postStub.resolves({235 data,236 });237 request(server)238 .post(apiPath)239 .set({240 Authorization: `Bearer ${jwts.admin}`,241 })242 .send(testBody)243 .expect(200)244 .end((err) => {245 if (err) {246 return done(err);247 }248 return done();249 });250 });251 it.skip('should return 200 response with no matching referenceLookup', (done) => {252 sandbox.stub(axios, 'get').resolves({});253 const data = {254 topic_id: 1,255 };256 sandbox.stub(axios, 'post').resolves({257 status: 200,258 data,259 });260 request(server)261 .post(apiPath)262 .set({263 Authorization: `Bearer ${jwts.admin}`,264 })265 .send(testBody2)266 .expect(200)267 .end((err, res) => {268 if (err) {269 return done(err);270 }271 res.body.should.have.propertyByPath('result', 'content', 'topic_id').eql(data.topic_id);272 return done();273 });274 });275 it('should return 500 response if error to createPrivatePost with reject', (done) => {276 const data = {277 result: {278 status: 200,279 content: 'content',280 },281 };282 sandbox.stub(axios, 'get').resolves({283 data,284 });285 sandbox.stub(axios, 'post').rejects({});286 request(server)287 .post(apiPath)288 .set({289 Authorization: `Bearer ${jwts.admin}`,290 })291 .send(testBody)292 .expect(500)293 .end((err) => {294 if (err) {295 return done(err);296 }297 return done();298 });299 });300 it('should return 500 response if error to createPrivatePost with invalid status', (done) => {301 const data = {302 result: {303 status: 200,304 content: 'content',305 },306 };307 sandbox.stub(axios, 'get').resolves({308 data,309 });310 sandbox.stub(axios, 'post').resolves({311 status: 500,312 });313 request(server)314 .post(apiPath)315 .set({316 Authorization: `Bearer ${jwts.admin}`,317 })318 .send(testBody)319 .expect(500)320 .end((err) => {321 if (err) {322 return done(err);323 }324 return done();325 });326 });327 it.skip('should return 200 response if success to createPrivatePost', (done) => {328 const data = {329 result: {330 status: 200,331 content: 'content',332 },333 topic_id: 1,334 };335 sandbox.stub(axios, 'get').resolves({336 data,337 });338 sandbox.stub(axios, 'post').resolves({339 data,340 });341 request(server)342 .post(apiPath)343 .set({344 Authorization: `Bearer ${jwts.admin}`,345 })346 .send(testBody)347 .expect(200)348 .end((err) => {349 if (err) {350 return done(err);351 }352 return done();353 });354 });355 // eslint-disable-next-line356 it.skip('should return 200 response if error on first createPrivatePost, success to create user and success on second createPrivatePost', (done) => {357 const data = {358 result: {359 status: 200,360 content: 'content',361 },362 topic_id: 1,363 };364 const stub = sandbox.stub(axios, 'get');365 stub.withArgs(`/users/${username}.json`, sinon.match.any)366 .resolves({});367 stub.withArgs(`${config.memberServiceUrl}/${username}`, sinon.match.any)368 .resolves({369 data: {370 result: {371 status: 200,372 content: {373 handle: username,374 userId: 1,375 firstName: 'fname',376 lastName: 'lName',377 email: 'some@abc.com',378 },379 } },380 });381 stub.resolves({382 data,383 });384 const postStub = sandbox.stub(axios, 'post');385 const userTokenStub = sandbox.stub(util, 'getSystemUserToken').resolves('token'); // eslint-disable-line386 postStub.onFirstCall().returnsPromise = postStub.returnsPromise;387 postStub.onFirstCall().rejects({388 response: {389 status: 403,390 },391 });392 postStub.resolves({393 data,394 });395 request(server)396 .post(apiPath)397 .set({398 Authorization: `Bearer ${jwts.admin}`,399 })400 .send(testBody)401 .expect(200)402 .end((err) => {403 if (err) {404 return done(err);405 }406 return done();407 });408 });409 // eslint-disable-next-line410 it.skip('should return 200 response if error on first createPrivatePost, success to create user and success on third createPrivatePost', (done) => {411 const data = {412 result: {413 status: 200,414 content: 'content',415 },416 topic_id: 1,417 };418 const stub = sandbox.stub(axios, 'get');419 stub.withArgs(`/users/${username}.json`, sinon.match.any)420 .resolves({});421 stub.withArgs(`${config.memberServiceUrl}/${username}`, sinon.match.any)422 .resolves({423 data,424 });425 stub.resolves({426 data,427 });428 const postStub = sandbox.stub(axios, 'post');429 postStub.onFirstCall().returnsPromise = postStub.returnsPromise;430 postStub.onSecondCall().returnsPromise = postStub.returnsPromise;431 postStub.onFirstCall().rejects({432 response: {433 status: 403,434 },435 });436 postStub.onSecondCall().rejects({437 response: {438 status: 403,439 },440 });441 postStub.resolves({442 data,443 });444 const configStub = sandbox.stub(config, 'get');445 configStub.withArgs('createTopicRetryDelay').returns(0);446 configStub.withArgs('createTopicTimeout').returns(2000);447 request(server)448 .post(apiPath)449 .set({450 Authorization: `Bearer ${jwts.admin}`,451 })452 .send(testBody)453 .expect(200)454 .end((err) => {455 if (err) {456 return done(err);457 }458 return done();459 });460 });...
index-test.js
Source:index-test.js
...4import createStore from '../../src/index';5stubPromise(sinon);6const DynamoStore = createStore({Store: null});7const mockClient = overrides => Object.assign({8 init: sinon.stub().returnsPromise().resolves(),9 deleteExpired: sinon.stub().returnsPromise().resolves({scanned: 0, deleted: 0})10}, overrides);11withFakeTimers('Should only be able to get valid session with the correct id', t => {12 const ids = {13 valid: 'valid',14 expired: 'expired',15 invalid: 'invalid',16 error: 'error'17 };18 const content = {foo: 'bar'};19 const get = sinon.stub();20 get.withArgs(ids.valid).returnsPromise().resolves({expires: Date.now() + 500, content});21 get.withArgs(ids.expired).returnsPromise().resolves({expires: Date.now() - 500, content});22 get.withArgs(ids.invalid).returnsPromise().resolves();23 get.returnsPromise().rejects('some error');24 const store = new DynamoStore({client: mockClient({get}), tableName: 'foo'});25 store.get(ids.valid, (err, session) => {26 t.comment('get session with correct id');27 t.false(err, 'error should be null');28 t.deepEqual(session, content, 'session should be as expected');29 });30 store.get(ids.expired, (err, session) => {31 t.comment('get session with expired id');32 t.false(err, 'error should be null');33 t.false(session, 'session should be null');34 });35 store.get(ids.invalid, (err, session) => {36 t.comment('get session with invalid id');37 t.false(err, 'error should be null');38 t.false(session, 'session should be null');39 });40 store.get(ids.error, (err, session) => {41 t.comment('store.get returns error');42 t.equal(err, 'some error', 'error should be as expected');43 t.false(session, 'session should be null');44 t.end();45 });46});47withFakeTimers('Set should update lastModified', (t, clock) => {48 const now = 123;49 clock.tick(now);50 const id = 'abc';51 const session = {foo: 'bar', cookie: {expires: 321}, lastModified: 3};52 const content = Object.assign({}, session, {lastModified: now});53 const put = sinon.stub();54 put.withArgs(id, 321, content).returnsPromise().resolves();55 put.returnsPromise().rejects('some error');56 const store = new DynamoStore({client: mockClient({put}), tableName: 'foo'});57 store.set(id, session, err => {58 t.false(err, 'error should be null');59 });60 store.set('error', session, err => {61 t.equal(err, 'some error', 'error should be as expected');62 t.end();63 });64});65withFakeTimers('Set should not update lastModified if touchAfter is disabled', t => {66 const id = 'abc';67 const session = {foo: 'bar', cookie: {expires: 321}};68 const put = sinon.stub();69 put.withArgs(id, 321, session).returnsPromise().resolves();70 put.returnsPromise().rejects('some error');71 const store = new DynamoStore({client: mockClient({put}), tableName: 'foo', touchAfter: 0});72 store.set(id, session, err => {73 t.false(err, 'error should be null');74 t.true(put.called, 'put should be called');75 t.end();76 });77});78withFakeTimers('Should only touch if not modified recently', (t, clock) => {79 const now = 123456789;80 clock.tick(now);81 const id = 'abc';82 const base = {foo: 'bar', cookie: {expires: 321}};83 const recentSession = () => Object.assign({lastModified: now - 100}, base);84 const oldSession = () => Object.assign({lastModified: now - 100000}, base);85 const put = sinon.stub();86 put.withArgs(id, 321).returnsPromise().resolves();87 put.returnsPromise().rejects('some error');88 const store = new DynamoStore({89 client: mockClient({put}),90 tableName: 'foo',91 touchAfter: 30092 });93 store.touch(id, recentSession(), err => {94 t.comment('touch should do nothing for a recently modified session');95 t.false(err, 'error should be null');96 t.equal(put.callCount, 0, 'put should not have been called');97 });98 store.touch(id, oldSession(), err => {99 t.comment('touch should update expires for older sessions');100 t.false(err, 'error should be null');101 t.equal(put.callCount, 1, 'put should have been called once');102 });103 store.touch('error', oldSession(), err => {104 t.comment('errors should be passed to callback');105 t.equal(err, 'some error', 'error should be as expected');106 t.equal(put.callCount, 2, 'put should have been called twice');107 });108 const setExpires = sinon.stub();109 setExpires.withArgs(id, 321).returnsPromise().resolves();110 setExpires.returnsPromise().rejects('some error');111 const alwaysTouch = new DynamoStore({112 client: mockClient({setExpires}),113 tableName: 'foo',114 touchAfter: 0115 });116 alwaysTouch.touch(id, recentSession(), err => {117 t.comment('touch should update expires for recently modified session');118 t.false(err, 'error should be null');119 t.equal(setExpires.callCount, 1, 'set expires should have been called once');120 });121 alwaysTouch.touch(id, oldSession(), err => {122 t.comment('touch should update expires for older sessions');123 t.false(err, 'error should be null');124 t.equal(setExpires.callCount, 2, 'set expires should have been called twice');125 t.end();126 });127});128withFakeTimers('Should destroy sessions', t => {129 const id = 'abc';130 const stub = sinon.stub();131 stub.withArgs(id).returnsPromise().resolves();132 stub.returnsPromise().rejects('some error');133 const store = new DynamoStore({134 client: mockClient({delete: stub}),135 tableName: 'foo'136 });137 store.destroy(id, err => {138 t.comment('should destroy');139 t.false(err, 'error should be null');140 });141 store.destroy('foo', err => {142 t.comment('should pass error to callback');143 t.equal(err, 'some error', 'error should be as expected');144 t.end();145 });146});147withFakeTimers('Should work out expires', (t, clock) => {148 clock.tick(500);149 const store = new DynamoStore({client: mockClient(), tableName: 'foo', ttl: 50});150 t.equal(store.getExpires({cookie: {expires: 123}}), 123, 'should use expires number');151 t.equal(store.getExpires({cookie: {expires: '01/01/1970 00:00:05Z'}}), 5000,152 'should use expires string');153 t.equal(store.getExpires({}), 500 + 50, 'should fall back to now + ttl');154 t.end();155});156withFakeTimers('Should cleanup', (t, clock) => {157 const deleteExpired = sinon.stub().returnsPromise().resolves({scanned: 200, deleted: 50});158 const logger = sinon.stub();159 (() => new DynamoStore({160 client: mockClient({deleteExpired}),161 tableName: 'foo',162 cleanupInterval: 50,163 touchAfter: 500,164 err: logger165 }))();166 t.equal(deleteExpired.callCount, 0, 'should not have called deleteExpired');167 clock.tick(55);168 t.equal(deleteExpired.callCount, 1, 'should have called deleteExpired');169 clock.tick(55);170 t.equal(deleteExpired.callCount, 2, 'should have called deleteExpired');171 clock.tick(55);172 t.equal(deleteExpired.callCount, 3, 'should have called deleteExpired');173 t.equal(logger.callCount, 0, 'should not call error log');174 t.end();175});176withFakeTimers('Should not cleanup if no cleanupInterval set', (t, clock) => {177 const deleteExpired = sinon.stub();178 (() => new DynamoStore({179 client: mockClient({deleteExpired}),180 tableName: 'foo',181 cleanupInterval: 0182 }))();183 clock.tick(55);184 t.equal(deleteExpired.callCount, 0, 'should not have called deleteExpired');185 clock.tick(55);186 t.equal(deleteExpired.callCount, 0, 'should not have called deleteExpired');187 t.end();188});189withFakeTimers('Should still try to cleanup even if errors', (t, clock) => {190 const deleteExpired = sinon.stub().returnsPromise().rejects();191 const logger = sinon.stub();192 (() => new DynamoStore({193 client: mockClient({deleteExpired}),194 tableName: 'foo',195 cleanupInterval: 50,196 err: logger197 }))();198 t.equal(deleteExpired.callCount, 0, 'should not have called deleteExpired');199 clock.tick(55);200 t.equal(deleteExpired.callCount, 1, 'should have called deleteExpired');201 t.equal(logger.callCount, 1, 'should call error log');202 deleteExpired.rejects(); // reset the stub203 clock.tick(55);204 t.equal(deleteExpired.callCount, 2, 'should have called deleteExpired');...
monitor.js
Source:monitor.js
...78 });79 });80 describe('success()', function() {81 it('should fail getting error count', function(done) {82 sandbox.stub(aws, 'fetchCount').returnsPromise().rejects(error);83 var cb = function(err, res) {84 err.should.be.equal(error);85 should.not.exist(res);86 aws.fetchCount.calledOnce.should.be.true();87 done();88 };89 monitor.success(site, log, cb);90 });91 it('should get a count of 0', function(done) {92 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(0);93 var cb = function(err, res) {94 should.not.exist(err);95 should.not.exist(res);96 aws.fetchCount.calledOnce.should.be.true();97 done();98 };99 monitor.success(site, log, cb);100 });101 it('should fail sending SNS message', function(done) {102 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);103 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {104 done(error);105 });106 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {107 done();108 });109 var cb = function(err, res) {110 err.should.be.equal(error);111 should.not.exist(res);112 aws.fetchCount.calledOnce.should.be.true();113 aws.snsMessage.calledOnce.should.be.true();114 done();115 };116 monitor.success(site, log, cb);117 });118 it('should fail storing error count', function(done) {119 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);120 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {121 done();122 });123 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {124 done(error);125 });126 var cb = function(err, res) {127 err.should.be.equal(error);128 should.not.exist(res);129 aws.fetchCount.calledOnce.should.be.true();130 aws.storeCount.calledOnce.should.be.true();131 done();132 };133 monitor.success(site, log, cb);134 });135 it('should get a count of 3', function(done) {136 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);137 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {138 done();139 });140 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {141 done();142 });143 var cb = function(err, res) {144 should.not.exist(err);145 should.not.exist(res);146 aws.fetchCount.calledOnce.should.be.true();147 aws.snsMessage.calledOnce.should.be.true();148 aws.storeCount.calledOnce.should.be.true();149 done();150 };151 monitor.success(site, log, cb);152 });153 });154 describe('fail()', function() {155 it('should fail getting error count', function(done) {156 sandbox.stub(aws, 'fetchCount').returnsPromise().rejects(error);157 var cb = function(err, res) {158 err.should.be.equal(error);159 should.not.exist(res);160 aws.fetchCount.calledOnce.should.be.true();161 done();162 };163 monitor.fail(site, log, cb);164 });165 it('should get a count of 10', function(done) {166 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(10);167 var cb = function(err, res) {168 should.not.exist(err);169 should.not.exist(res);170 aws.fetchCount.calledOnce.should.be.true();171 done();172 };173 monitor.fail(site, log, cb);174 });175 it('should fail sending SNS message', function(done) {176 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);177 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {178 done(error);179 });180 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {181 done();182 });183 var cb = function(err, res) {184 err.should.be.equal(error);185 should.not.exist(res);186 aws.fetchCount.calledOnce.should.be.true();187 aws.snsMessage.calledOnce.should.be.true();188 done();189 };190 monitor.fail(site, log, cb);191 });192 it('should fail storing error count', function(done) {193 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);194 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {195 done();196 });197 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {198 done(error);199 });200 var cb = function(err, res) {201 err.should.be.equal(error);202 should.not.exist(res);203 aws.fetchCount.calledOnce.should.be.true();204 aws.storeCount.calledOnce.should.be.true();205 done();206 };207 monitor.fail(site, log, cb);208 });209 it('should get a count of 3', function(done) {210 sandbox.stub(aws, 'fetchCount').returnsPromise().resolves(3);211 sandbox.stub(aws, 'snsMessage', function(message, topic, region, log, done) {212 done();213 });214 sandbox.stub(aws, 'storeCount', function(counter, bucket, key, region, log, done) {215 done();216 });217 var cb = function(err, res) {218 should.not.exist(err);219 should.not.exist(res);220 aws.fetchCount.calledOnce.should.be.true();221 aws.snsMessage.calledOnce.should.be.true();222 aws.storeCount.calledOnce.should.be.true();223 done();224 };...
validate.js
Source:validate.js
1const _ = require('lodash');2const Ajv = require('ajv');3var stack;4const getSchemaReferencesErrorMessages = ({5 allSchemas,6 parametersAndSchemas,7 returnSchema,8 returnsPromise,9}) => {10 const schemaReferenceAndAnnotationNameTuples = parametersAndSchemas11 .filter(({ schema }) => _.isString(schema))12 .map(({ schema: schemaReference, schemaName }) => [schemaReference, `"${schemaName}"`]);13 if (_.isString(returnSchema)) {14 schemaReferenceAndAnnotationNameTuples.push([returnSchema, returnsPromise ? '"resolve"' : '"return"']);15 }16 const allErrorMessages = schemaReferenceAndAnnotationNameTuples.reduce(17 (errorMessages, [schemaReference, annotationName]) => {18 if (!_.has(allSchemas, schemaReference)) {19 errorMessages.push(`Unknown schema reference "${schemaReference}" for ${annotationName}`);20 }21 return errorMessages;22 },23 [],24 );25 return allErrorMessages;26};27const getValidationErrorMessage = (schema, value, { ajv }) => {28 const isValid = ajv.validate(schema, value);29 return isValid ? null : ajv.errorsText();30};31const validateReturnValue = (returnedValue, options) => {32 const { returnSchema, returnsPromise } = options;33 const modifier = returnsPromise ? 'resolved value' : 'return value';34 if (returnSchema === null) {35 if (returnedValue === undefined) {36 return;37 }38 console.log(stack);39 throw Error(`${modifier} should be undefined`);40 }41 const errorMessage = getValidationErrorMessage(returnSchema, returnedValue, options);42 if (errorMessage) {43 console.log(stack);44 const modifiedMessage = errorMessage.replace(/data/g, modifier);45 throw Error(modifiedMessage);46 }47};48module.exports.buildValidate = (additionalSchemas = {}) => {49 if (!_.isPlainObject(additionalSchemas)) {50 throw Error('Non plain object passed to "buildValidate"');51 }52 {53 const invalidSchemaNames = _(additionalSchemas)54 .pickBy((schema, name) => name.startsWith('jss/'))55 .map((schema, name) => `"${name}"`)56 .join(', ');57 if (!_.isEmpty(invalidSchemaNames)) {58 throw Error(`Schemas passed to "buildValidate" must not have reserved prefix "jss/". Invalid schemas: [${invalidSchemaNames}]`);59 }60 }61 {62 const invalidSchemaNames = _(additionalSchemas)63 .pickBy((schema) => !_.isPlainObject(schema) && !_.isBoolean(schema))64 .map((schema, name) => `"${name}"`)65 .join(', ');66 if (!_.isEmpty(invalidSchemaNames)) {67 throw Error(`Schemas passed to "buildValidate" must be booleans or objects. Invalid schemas: [${invalidSchemaNames}]`);68 }69 }70 const ajv = new Ajv();71 const jssSchemas = {72 'jss/array': { type: 'array' },73 'jss/boolean': { type: 'boolean' },74 'jss/integer': { type: 'integer' },75 'jss/null': { type: 'null' },76 'jss/number': { type: 'number' },77 'jss/object': { type: 'object' },78 'jss/string': { type: 'string' },79 };80 const allSchemas = {81 ...additionalSchemas,82 ...jssSchemas,83 };84 _.forEach(allSchemas, (schema, name) => {85 try {86 ajv.addSchema(schema, name);87 } catch (error) {88 const message = error.message.replace(/data/g, `"${name}"`);89 throw Error(message);90 }91 });92 const validate = (parameterAndSchemaTuples, returnSchema, wrappedFunction, { returnsPromise = false } = {}) => {93 stack = new Error('Original Stack Trace').stack;94 const parametersAndSchemas = _.isArray(parameterAndSchemaTuples)95 ? parameterAndSchemaTuples.map(([parameter, schema], index) => ({96 parameter,97 schema,98 schemaName: `params[${index}]`,99 parameterName: `parameters[${index}]`,100 }))101 : _.entries(parameterAndSchemaTuples).map(([schemaName, [parameter, schema]]) => ({102 parameter,103 schema,104 schemaName,105 parameterName: `"${schemaName}"`,106 }));107 const options = {108 ajv,109 allSchemas,110 parametersAndSchemas,111 returnSchema,112 wrappedFunction,113 returnsPromise,114 };115 const referenceErrorMessages = getSchemaReferencesErrorMessages(options);116 if (referenceErrorMessages.length > 0) {117 const errorMessage = referenceErrorMessages.join('\n');118 if (returnsPromise) {119 return Promise.reject(Error(errorMessage));120 }121 throw Error(errorMessage);122 }123 const parameterErrorMessages = parametersAndSchemas.reduce(124 (errorMessages, { parameter, schema, parameterName }) => {125 const errorMessage = getValidationErrorMessage(schema, parameter, options);126 if (errorMessage) {127 const modifiedMessage = errorMessage.replace(/data/g, parameterName);128 errorMessages.push(modifiedMessage);129 }130 return errorMessages;131 },132 [],133 );134 if (parameterErrorMessages.length > 0) {135 const errorMessage = parameterErrorMessages.join('\n');136 if (returnsPromise) {137 return Promise.reject(Error(errorMessage));138 }139 throw Error(errorMessage);140 }141 const returnedValue = wrappedFunction();142 if (returnsPromise) {143 if (!(returnedValue instanceof Promise)) {144 return Promise.reject(Error('return value should be Promise'));145 }146 return returnedValue.then((resolvedValue) => {147 validateReturnValue(resolvedValue, options);148 return resolvedValue;149 });150 }151 if (returnedValue instanceof Promise) {152 return returnedValue153 .finally(() => {154 throw Error('return value should not be a Promise. If a Promise is desired then define a "resolve" schema instead of a "return" schema');155 });156 }157 validateReturnValue(returnedValue, options);158 return returnedValue;159 };160 return validate;...
your-code.test.js
Source:your-code.test.js
...9 return true;10 } 11 return false;12}13function returnsPromise(f) {14 if (15 f.constructor.name === 'AsyncFunction' ||16 (typeof f === 'function' && isPromise(f()))17 ) {18 return true;19 }20 throw new Error(f.name + " does not return fetch")21}22const unmockedFetch = global.fetch;23beforeEach(() => {24 global.fetch = (url, options) => {25 return new Promise((resolve) => resolve({url, options}));26 }27});28afterEach(() => {29 global.fetch = unmockedFetch;30});31describe("fetch call helper functions", () => {32 describe("getAllDogs()", () => {33 test("should return a fetch call",(done) => {34 expect(() => returnsPromise(getAllDogs)).not.toThrowError();35 done()36 });37 test("should make a fetch request to the correct endpoint", async () => {38 const res = await getAllDogs()39 expect(res.url).toBe("/dogs")40 });41 test("should not have any options passed to fetch", async () => {42 const res = await getAllDogs()43 expect(res.options).toBe(undefined)44 });45 });46 describe("getDogNumberTwo()", () => {47 test("should return a fetch call", (done) => {48 expect(() => returnsPromise(getDogNumberTwo)).not.toThrowError();49 done();50 });51 test("should make a fetch request to the correct endpoint", async() => {52 const res = await getDogNumberTwo();53 expect(res.url).toBe("/dogs/2");54 })55 });56 describe("postNewDog()", () => {57 test("should return a fetch call", (done) => {58 expect(() => returnsPromise(postNewDog)).not.toThrowError();59 done();60 });61 test("should make a request to the correct endpoint", async () => {62 const res = await postNewDog()63 expect(res.url).toBe("/dogs")64 });65 test("should set the correct method", async() => {66 expect.assertions(1);67 const res = await postNewDog();68 expect(/^POST$/i.test(res.options.method)).toBe(true);69 })70 test("should set the appropriate headers", async () => { 71 expect.assertions(2);72 const res = await postNewDog();73 const [[key, value]] = Object.entries(res.options.headers);74 console.log(key, value)75 expect(/^Content-Type$/i.test(key)).toBe(true);76 expect(/^application\/x-www-form-urlencoded$/i.test(value)).toBe(true);77 });78 test("should send the appropriate body", async () => {79 expect.assertions(3);80 const res = await postNewDog();81 expect(res.options.body instanceof URLSearchParams).toBe(true);82 expect(res.options.body.has("name")).toBe(true)83 expect(res.options.body.has("age")).toBe(true)84 });85 });86 describe("postNewDogV2(name, age)", () => {87 test("should return a fetch call", (done) => {88 expect(() => returnsPromise(postNewDogV2)).not.toThrowError();89 done();90 });91 test("should make a request to the correct endpoint", async () => {92 const res = await postNewDogV2()93 expect(res.url).toBe("/dogs")94 });95 test("should set the appropriate headers", async () => { 96 expect.assertions(2);97 const res = await postNewDogV2("Rosie",1);98 const [[key, value]] = Object.entries(res.options.headers);99 expect(/^Content-Type$/i.test(key)).toBe(true);100 expect(/^application\/x-www-form-urlencoded$/i.test(value)).toBe(true);101 });102 test("should send the appropriate body", async () => {103 expect.assertions(5);104 const res = await postNewDogV2("ckyussk1q0000oiv5842u3dri",8);105 expect(res.options.body instanceof URLSearchParams).toBe(true);106 expect(res.options.body.has("name")).toBe(true)107 expect(res.options.body.has("age")).toBe(true);108 const bodyString = res.options.body.toString()109 expect(bodyString.includes("ckyussk1q0000oiv5842u3dri")).toBe(true)110 expect(bodyString.includes(8)).toBe(true)111 112 });113 });114 describe("deleteDog(id)", () => {115 test("should return a fetch call", (done) => {116 expect(() => returnsPromise(deleteDog)).not.toThrowError();117 done();118 });119 test("should set the appropriate method", async () => {120 expect.assertions(1);121 const res = await deleteDog(1)122 expect(/POST/i.test(res.options.method)).toBe(true);123 })124 test("should set the appropriate headers", async () => { 125 expect.assertions(2);126 const res = await deleteDog(1);127 const [[key, value]] = Object.entries(res.options.headers);128 expect(/AUTH/i.test(key)).toBe(true);129 expect(value).toBe("ckyut5wau0000jyv5bsrud90y");130 });...
dynamo-test.js
Source:dynamo-test.js
...4import dynamo from '../../src/dynamo';5stubPromise(sinon);6const tableName = 'foo';7test('Init should succeed when no errors', () => {8 const promise = sinon.stub().withArgs({TableName: tableName}).returnsPromise().resolves();9 const awsClient = {describeTable: () => ({promise})};10 return dynamo({awsClient, tableName}).init();11});12test('Init should pass errors on', t => {13 const promise = sinon.stub().withArgs({TableName: tableName}).returnsPromise()14 .rejects(new TypeError());15 const awsClient = {describeTable: () => ({promise})};16 return t.shouldFail(dynamo({awsClient, tableName}).init(), TypeError, 'should return type error');17});18test('Should be able to get a session', t => {19 const id = 'abc';20 const promise = sinon.stub()21 .withArgs({22 TableName: tableName,23 ConsistentRead: true,24 Key: {id: {S: id}}25 }).returnsPromise()26 .resolves({27 Item: {28 content: {S: '{"foo": 42}'},29 expires: {N: '123'}30 }31 });32 const awsClient = {getItem: () => ({promise})};33 return dynamo({awsClient, tableName})34 .get(id)35 .then(({expires, content}) => {36 t.equal(expires, 123, 'expires should be 123');37 t.deepEqual(content, {foo: 42}, 'content should be as expected');38 });39});40test('Should be able to not find a session', t => {41 const promise = sinon.stub()42 .withArgs().returnsPromise()43 .resolves({Item: {}});44 const awsClient = {getItem: () => ({promise})};45 return dynamo({awsClient, tableName})46 .get('abc')47 .then(row => t.false(row, 'should resolve with null'));48});49test('Should reject for invalid json content', t => {50 const promise = sinon.stub()51 .withArgs().returnsPromise()52 .resolves({53 Item: {54 content: {S: '[}not json'},55 expires: {N: '123'}56 }57 });58 const awsClient = {getItem: () => ({promise})};59 return t.shouldFail(dynamo({awsClient, tableName}).get('abc'), SyntaxError);60});61test('Should be able to put a session', () => {62 const id = 'abc';63 const expires = '123';64 const content = {foo: 'bar'};65 const promise = sinon.stub()66 .withArgs({67 TableName: tableName,68 Item: {69 id: {S: id},70 expires: {N: expires},71 content: {S: JSON.stringify(content)}72 }73 }).returnsPromise()74 .resolves();75 const awsClient = {putItem: () => ({promise})};76 return dynamo({awsClient, tableName}).put(id, expires, content);77});78test('Should pass put errors on', t => {79 const promise = sinon.stub().withArgs({TableName: tableName}).returnsPromise()80 .rejects(new TypeError());81 const awsClient = {putItem: () => ({promise})};82 return t.shouldFail(dynamo({awsClient, tableName}).put('abc', '123', '42'), TypeError);83});84test('Should be able to delete a session', () => {85 const id = 'abc';86 const promise = sinon.stub()87 .withArgs({88 TableName: tableName,89 Key: {id: {S: id}}90 })91 .returnsPromise()92 .resolves();93 const awsClient = {deleteItem: () => ({promise})};94 return dynamo({awsClient, tableName}).delete(id);95});96test('Should pass delete errors on', t => {97 const promise = sinon.stub().withArgs({TableName: tableName}).returnsPromise()98 .rejects(new TypeError());99 const awsClient = {deleteItem: () => ({promise})};100 return t.shouldFail(dynamo({awsClient, tableName}).delete('abc'), TypeError);101});102const scanQuery = (when, startKey = null) => ({103 TableName: tableName,104 FilterExpression: 'expires < :when',105 ExpressionAttributeValues: {':when': {N: when.toString()}},106 ProjectionExpression: 'id',107 ExclusiveStartKey: startKey108});109test('Should handle when scan returns no results', t => {110 const promise = sinon.stub()111 .withArgs(scanQuery(200))112 .returnsPromise()113 .resolves({Items: [], ScannedCount: 34});114 const awsClient = {scan: () => ({promise})};115 return dynamo({awsClient, tableName})116 .deleteExpired(200)117 .then(({scanned, deleted}) => {118 t.equal(scanned, 34, 'scanned should be 34');119 t.equal(deleted, 0, 'deleted should be 0');120 });121});122test('Should pass errors on when deleteing expired', t => {123 const promise = sinon.stub().withArgs(scanQuery(200)).returnsPromise()124 .rejects(new TypeError());125 const awsClient = {scan: () => ({promise})};126 return t.shouldFail(dynamo({awsClient, tableName}).deleteExpired(200), TypeError);127});128test('Should be able to delete one page of results', t => {129 const promise = sinon.stub()130 .withArgs(scanQuery(200))131 .returnsPromise()132 .resolves({133 Items: [134 {id: {S: 'john'}},135 {id: {S: 'paul'}}136 ],137 ScannedCount: 34138 });139 const awsClient = {scan: () => ({promise})};140 return dynamo({awsClient, tableName})141 .deleteExpired(200)142 .then(({scanned, deleted}) => {143 t.equal(scanned, 34, 'scanned should be 34');144 t.equal(deleted, 2, 'deleted should be 2');145 });...
index.spec.js
Source:index.spec.js
...5const {alerts} = require(`${SRC}/alerts`);6describe('alerts', () => {7 let sandbox = sinon.sandbox.create();8 beforeEach(() => {9 sandbox.stub(previousState, 'get').returnsPromise();10 sandbox.stub(previousState, 'update').returnsPromise();11 sandbox.stub(CurrentSlots, 'currentSlots').returnsPromise();12 sandbox.stub(Login, 'login').returnsPromise();13 })14 afterEach(() => {15 sandbox.restore();16 })17 it('should get current slots using previous state login details', (done) => {18 previousState.get.resolves({ loginDetails: 'previous-login-details', slots: {a: {}} });19 CurrentSlots.currentSlots.resolves({a: {}});20 previousState.update.resolves();21 alerts()22 .then(() => {23 CurrentSlots.currentSlots.calledWith('previous-login-details').should.eql(true);24 done();25 });26 })...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('returnsPromise', () => {2 return Cypress.automation('returnsPromise')3})4Cypress.Commands.add('returnsPromise', () => {5 return Cypress.automation('returnsPromise')6})7describe('test', () => {8 it('test', () => {9 cy.returnsPromise().then((result) => {10 console.log(result)11 })12 })13})14Cypress.Commands.add('returnsPromise', () => {15 return Cypress.automation('returnsPromise')16})17describe('test', () => {18 it('test', () => {19 cy.returnsPromise().then((result) => {20 console.log(result)21 })22 })23})24Cypress.Commands.add('returnsPromise', () => {25 return Cypress.automation('returnsPromise')26})27describe('test', () => {28 it('test', () => {29 cy.returnsPromise().then((result) => {30 console.log(result)31 })32 })33})34Cypress.Commands.add('returnsPromise', () => {35 return Cypress.automation('returnsPromise')36})37describe('test', () => {38 it('test', () => {39 cy.returnsPromise().then((result) => {40 console.log(result)41 })42 })43})44Cypress.Commands.add('returnsPromise', () => {45 return Cypress.automation('returnsPromise')46})47describe('test', () => {48 it('test', () => {49 cy.returnsPromise().then((result) => {50 console.log(result)51 })52 })53})54Cypress.Commands.add('returnsPromise', () => {55 return Cypress.automation('returnsPromise')56})57describe('test', () => {58 it('test', () => {59 cy.returnsPromise().then
Using AI Code Generation
1cy.returnsPromise().then((result) => {2});3Cypress.Commands.add('returnsPromise', () => {4 return new Cypress.Promise((resolve, reject) => {5 resolve('result');6 });7});
Using AI Code Generation
1describe('my test', () => {2 it('works', () => {3 cy.wrap({}).then(() => {4 return Cypress.Promise.resolve('foo').then(returnsPromise)5 })6 })7})8const returnsPromise = () => {9 return new Cypress.Promise((resolve, reject) => {10 setTimeout(() => {11 resolve('bar')12 }, 1000)13 })14}
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.returnsPromise().then((value) => {4 expect(value).to.equal('foo')5 })6 })7})8Cypress.Commands.add('returnsPromise', () => {9 return Cypress.Promise.resolve('foo')10})
Using AI Code Generation
1const returnsPromise = (num) => {2 return new Cypress.Promise((resolve, reject) => {3 if (num === 4) {4 resolve('Hey, the number is 4')5 } else {6 reject('Sorry, the number is not 4')7 }8 })9}10describe('My First Test', () => {11 it('Does not do much!', () => {12 cy.contains('type').click()13 cy.url().should('include', '/commands/actions')14 cy.get('.action-email')15 .type('
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!