Best JavaScript code snippet using mocha
init.test.js
Source:init.test.js
1'use strict'2// Node modules3const fs = require('fs')4// Dependency modules5const globs = require('globs')6// Dev Dependency modules7require('should')8const sinon = require('sinon')9require('should-sinon')10const Lab = require('lab')11// System Under Test (SUT)12const init = require('../init')13const lab = exports.lab = Lab.script()14const describe = lab.experiment15// const before = lab.before16// const after = lab.after17const beforeEach = lab.beforeEach18const afterEach = lab.afterEach19const it = lab.test20let s21const orderedEnvvars = [22 'NODE_ENV',23 'TEST_BOOLEAN',24 'TEST_NUMBER',25 'TEST_REQUIRED',26 'TEST_STRING1',27 'TEST_STRING2'28]29const orderedCommentEnvvars = [30 'COMMENTED_ENVVAR1',31 'COMMENTED_ENVVAR2'32]33const file1 = `34/*35 * Copyright (c) 2017 test1, All rights reserved36 */37'use strict';38require('dotenv-safe').load();39process.env.${orderedEnvvars[0]} = process.env.${orderedEnvvars[0]} || 'development';40const testObj = {41 testString: process.env.${orderedEnvvars[4]} || 'testString1',42 testNumber: process.env.${orderedEnvvars[2]} || 'testNumber',43 testBoolean: process.env.${orderedEnvvars[1]} || 'testBoolean',44 testRequired: process.env.${orderedEnvvars[3]}45};46/*47 * commentedEnvvar = process.env.${orderedCommentEnvvars[0]};48 */49`50const file2 = `51//52// Copyright (c) 2017 test2, All rights reserved53//54const testString = process.env.${orderedEnvvars[5]} || 'testString2';55const testNumber = process.env.${orderedEnvvars[2]} || 100;56const testBoolean = process.env.${orderedEnvvars[1]} || true;57const testRequired = process.env.${orderedEnvvars[3]};58// commentedEnvvar = process.env.${orderedCommentEnvvars[1]};59`60describe('dotenv-init', function () {61 beforeEach(function (done) {62 s = sinon.sandbox.create()63 done()64 })65 afterEach(function (done) {66 s.restore()67 done()68 })69 describe('#init() (parse)', function () {70 let defaultArgs71 let defaultGlobsResult72 let consoleLog73 let globsSync74 let statSync75 let fileStats76 let dirStats77 let readFileSync78 let writeFileSync79 beforeEach(function (done) {80 defaultArgs = {81 output: 'normal',82 fileOutput: 'normal',83 safe: false,84 comments: false,85 ignore: 'node_modules/**,test/**',86 filename: '.env',87 safeFilename: '.env.example',88 args: ['**.js']89 }90 defaultGlobsResult = ['file1.js', 'file2.js']91 fileStats = sinon.createStubInstance(fs.Stats)92 fileStats.isFile.returns(true)93 fileStats.isDirectory.returns(false)94 dirStats = sinon.createStubInstance(fs.Stats)95 dirStats.isFile.returns(false)96 fileStats.isDirectory.returns(true)97 consoleLog = sinon.stub(console, 'log')98 globsSync = sinon.stub(globs, 'sync')99 statSync = sinon.stub(fs, 'statSync')100 readFileSync = sinon.stub(fs, 'readFileSync')101 writeFileSync = sinon.stub(fs, 'writeFileSync')102 done()103 })104 afterEach(function (done) {105 consoleLog.restore()106 globsSync.restore()107 statSync.restore()108 readFileSync.restore()109 writeFileSync.restore()110 done()111 })112 it('takes option for console output', function (done) {113 globsSync.returns(defaultGlobsResult)114 statSync.returns(fileStats)115 readFileSync.returns(file1)116 defaultArgs.output = 'silent'117 init(defaultArgs)118 consoleLog.should.not.be.called()119 consoleLog.reset()120 defaultArgs.output = 'normal'121 init(defaultArgs)122 consoleLog.callCount.should.be.aboveOrEqual(1)123 const normalLength = consoleLog.args[0][0].length124 consoleLog.reset()125 defaultArgs.output = 'verbose'126 init(defaultArgs)127 consoleLog.callCount.should.be.aboveOrEqual(1)128 consoleLog.args[0][0].length.should.be.above(normalLength)129 done()130 })131 it('takes option for file output', function (done) {132 globsSync.returns(defaultGlobsResult)133 statSync.returns(fileStats)134 readFileSync.returns(file1)135 defaultArgs.fileOutput = 'minimal'136 init(defaultArgs)137 const minimalLength = writeFileSync.args[0][1].length138 minimalLength.should.be.above(0)139 writeFileSync.reset()140 defaultArgs.fileOutput = 'normal'141 statSync.returns(fileStats)142 init(defaultArgs)143 const normalLength = writeFileSync.args[0][1].length144 normalLength.should.be.above(minimalLength)145 writeFileSync.reset()146 defaultArgs.fileOutput = 'verbose'147 statSync.returns(fileStats)148 init(defaultArgs)149 writeFileSync.args[0][1].length.should.be.above(normalLength)150 done()151 })152 it('takes option for safe', function (done) {153 globsSync.returns(defaultGlobsResult)154 statSync.returns(fileStats)155 readFileSync.returns('empty file')156 defaultArgs.safe = true157 init(defaultArgs)158 writeFileSync.callCount.should.eql(2)159 done()160 })161 it('takes option for allowing comments', function (done) {162 globsSync.returns(defaultGlobsResult)163 statSync.returns(fileStats)164 readFileSync.withArgs(sinon.match('file1.js'), sinon.match.string).returns(file1)165 readFileSync.withArgs(sinon.match('file2.js'), sinon.match.string).returns(file2)166 defaultArgs.comments = true167 const envvars = init(defaultArgs)168 const orderedNames = orderedEnvvars169 .concat(orderedCommentEnvvars)170 .sort()171 .map((envvar) => { return { name: envvar } })172 envvars.should.containDeepOrdered(orderedNames)173 done()174 })175 it('takes option for ignore', function (done) {176 globsSync.returns(defaultGlobsResult)177 statSync.returns(fileStats)178 readFileSync.returns('empty file')179 defaultArgs.ignore = 'otherDir/**'180 init(defaultArgs)181 consoleLog.restore()182 globsSync.args[0][1].should.eql({ ignore: defaultArgs.ignore.split(',') })183 done()184 })185 it('takes option for ignore (empty string)', function (done) {186 globsSync.returns(defaultGlobsResult)187 statSync.returns(fileStats)188 readFileSync.returns('empty file')189 defaultArgs.ignore = ''190 init(defaultArgs)191 consoleLog.restore()192 globsSync.args[0][1].should.eql({ ignore: null })193 done()194 })195 it('takes option for filename', function (done) {196 globsSync.returns(defaultGlobsResult)197 statSync.returns(fileStats)198 readFileSync.returns('empty file')199 defaultArgs.filename = '.test'200 init(defaultArgs)201 consoleLog.restore()202 writeFileSync.args[0][0].should.eql(defaultArgs.filename)203 done()204 })205 it('takes option for safeFilename', function (done) {206 globsSync.returns(defaultGlobsResult)207 statSync.returns(fileStats)208 readFileSync.returns('empty file')209 defaultArgs.safe = true210 defaultArgs.safeFilename = '.test.example'211 init(defaultArgs)212 writeFileSync.args[1][0].should.eql(defaultArgs.safeFilename)213 done()214 })215 it('takes a list of files to scan as args', function (done) {216 globsSync.returns(defaultGlobsResult)217 statSync.returns(fileStats)218 readFileSync.withArgs(sinon.match('file1.js'), sinon.match.string).returns(file1)219 readFileSync.withArgs(sinon.match('file2.js'), sinon.match.string).returns(file2)220 init(defaultArgs)221 statSync.args[0][0].should.containEql(defaultGlobsResult[0])222 statSync.args[1][0].should.containEql(defaultGlobsResult[1])223 done()224 })225 it('should not allow options for filename and safeFilename be the same', function (done) {226 globsSync.returns(defaultGlobsResult)227 defaultArgs.safe = true228 defaultArgs.output = 'silent'229 defaultArgs.filename = '.test'230 defaultArgs.safeFilename = '.test'231 init(defaultArgs)232 consoleLog.should.not.be.called()233 statSync.should.not.be.called()234 defaultArgs.output = 'normal'235 init(defaultArgs)236 consoleLog.should.be.calledOnce()237 statSync.should.not.be.called()238 done()239 })240 it('should disregard safeFilename option if safe option is false', function (done) {241 globsSync.returns(defaultGlobsResult)242 statSync.returns(fileStats)243 readFileSync.returns('empty file')244 defaultArgs.filename = '.test'245 defaultArgs.safeFilename = '.test'246 init(defaultArgs)247 statSync.should.be.called()248 done()249 })250 it('should exclude file list items that are directories', function (done) {251 globsSync.returns(defaultGlobsResult)252 statSync.onFirstCall().returns(fileStats)253 .onSecondCall().returns(dirStats)254 readFileSync.returns(file1)255 init(defaultArgs)256 statSync.args[0][0].should.containEql(defaultGlobsResult[0])257 statSync.args[1][0].should.containEql(defaultGlobsResult[1])258 readFileSync.callCount.should.equal(1)259 done()260 })261 it('should exclude file list items that do not exist', function (done) {262 globsSync.returns(defaultGlobsResult)263 statSync.onFirstCall().throws()264 .onSecondCall().returns(fileStats)265 readFileSync.returns(file1)266 init(defaultArgs).should.not.throw()267 statSync.should.be.calledTwice()268 statSync.args[0][0].should.containEql(defaultGlobsResult[0])269 statSync.args[1][0].should.containEql(defaultGlobsResult[1])270 readFileSync.callCount.should.equal(1)271 done()272 })273 it('should exclude file list items that fail when removing comments', function (done) {274 globsSync.returns(defaultGlobsResult)275 statSync.returns(fileStats)276 readFileSync.onFirstCall().returns(file1)277 .onSecondCall().returns('#!/usr/bin/env node')278 init(defaultArgs).should.not.throw()279 statSync.should.be.calledTwice()280 statSync.args[0][0].should.containEql(defaultGlobsResult[0])281 statSync.args[1][0].should.containEql(defaultGlobsResult[1])282 readFileSync.callCount.should.equal(2)283 done()284 })285 it('should exit without writing files if file list is empty', function (done) {286 defaultArgs.args = []287 init(defaultArgs)288 readFileSync.should.not.be.called()289 writeFileSync.should.not.be.called()290 consoleLog.reset()291 defaultArgs.output = 'silent'292 init(defaultArgs)293 consoleLog.should.not.be.called()294 readFileSync.should.not.be.called()295 writeFileSync.should.not.be.called()296 done()297 })298 it('should scan all files for process environment variables', function (done) {299 globsSync.returns(defaultGlobsResult)300 statSync.returns(fileStats)301 readFileSync.withArgs(sinon.match('file1.js'), sinon.match.string).returns(file1)302 readFileSync.withArgs(sinon.match('file2.js'), sinon.match.string).returns(file2)303 const envvars = init(defaultArgs)304 statSync.args[0][0].should.containEql(defaultGlobsResult[0])305 statSync.args[1][0].should.containEql(defaultGlobsResult[1])306 const orderedNames = orderedEnvvars.map((envvar) => { return { name: envvar } })307 envvars.should.containDeepOrdered(orderedNames)308 const orderedCommentNames = orderedCommentEnvvars.map((envvar) => { return { name: envvar } })309 envvars.should.not.containDeepOrdered(orderedCommentNames)310 done()311 })312 })...
use-async-object-manager.fn.test.js
Source:use-async-object-manager.fn.test.js
1/* eslint-disable camelcase */2import '@samnbuk/react_db_client.helpers.enzyme-setup';3import React from 'react';4import { renderHook, act } from '@testing-library/react-hooks';5import { mount } from 'enzyme';6import { AsyncTest1, AsyncTest2 } from './use-async-object-manager.composition';7import { useAsyncObjectManager } from './use-async-object-manager';8import { act as actR } from 'react-dom/test-utils';9Date.now = jest.fn().mockImplementation(() => 0);10const loadedData = { loaded: 'data' };11const asyncGetDocument = jest.fn().mockImplementation(async () => loadedData);12const asyncPutDocument = jest.fn().mockImplementation(async () => ({ ok: true }));13const asyncPostDocument = jest.fn().mockImplementation(async () => ({ ok: true }));14const asyncDeleteDocument = jest.fn().mockImplementation(async () => ({ ok: true }));15const onSavedCallback = jest.fn();16const defaultArgs = {17 activeUid: 'demouid',18 collection: 'democollection',19 isNew: false,20 inputAdditionalData: {},21 schema: 'all',22 populate: 'all',23 loadOnInit: true,24 asyncGetDocument,25 asyncPutDocument,26 asyncPostDocument,27 asyncDeleteDocument,28 onSavedCallback,29};30describe('useAsyncObjectManager', () => {31 beforeAll(() => {32 jest.useFakeTimers();33 });34 afterAll(() => {35 jest.useRealTimers();36 });37 describe('Compositions', () => {38 test('should render asyncTest1', () => {39 actR(() => {40 mount(<AsyncTest1 />);41 });42 actR(() => {43 jest.runOnlyPendingTimers();44 });45 });46 /* TODO: Fix this test as having async issues */47 test.skip('should render asyncTest2', () => {48 actR(() => {49 mount(<AsyncTest2 />);50 });51 actR(() => {52 jest.runOnlyPendingTimers();53 });54 });55 });56 describe('Functional Tests', () => {57 beforeEach(() => {58 asyncGetDocument.mockClear();59 asyncPutDocument.mockClear();60 asyncPostDocument.mockClear();61 asyncDeleteDocument.mockClear();62 onSavedCallback.mockClear();63 });64 test('should call async get docs', async () => {65 const { result, waitForNextUpdate } = renderHook(() => useAsyncObjectManager(defaultArgs));66 expect(asyncGetDocument).toHaveBeenCalledWith(67 defaultArgs.collection,68 defaultArgs.activeUid,69 defaultArgs.schema,70 defaultArgs.populate71 );72 expect(result.current.loadedData).toEqual(null);73 expect(result.current.data).toEqual({74 ...defaultArgs.inputAdditionalData,75 uid: defaultArgs.activeUid,76 });77 await waitForNextUpdate();78 expect(result.current.loadedData).toEqual(loadedData);79 expect(result.current.data).toEqual({80 ...loadedData,81 ...defaultArgs.inputAdditionalData,82 uid: defaultArgs.activeUid,83 });84 });85 test('should save data', async () => {86 const { result, waitForNextUpdate } = renderHook(() => useAsyncObjectManager(defaultArgs));87 await waitForNextUpdate();88 act(() => {89 result.current.saveData();90 });91 await waitForNextUpdate();92 act(() => {93 jest.runOnlyPendingTimers();94 });95 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {96 ...loadedData,97 ...defaultArgs.inputAdditionalData,98 uid: defaultArgs.activeUid,99 });100 });101 test('should update form data', async () => {102 const { result, waitForNextUpdate } = renderHook(() => useAsyncObjectManager(defaultArgs));103 await waitForNextUpdate();104 expect(result.current.data).toEqual({105 ...loadedData,106 ...defaultArgs.inputAdditionalData,107 uid: defaultArgs.activeUid,108 });109 const editField = 'edit';110 const editValue = 'val';111 act(() => {112 result.current.updateFormData(editField, editValue);113 });114 expect(result.current.data).toEqual({115 ...loadedData,116 ...defaultArgs.inputAdditionalData,117 uid: defaultArgs.activeUid,118 [editField]: editValue,119 });120 });121 test('should update form data and save', async () => {122 const { result, waitForNextUpdate } = renderHook(() => useAsyncObjectManager(defaultArgs));123 await waitForNextUpdate();124 expect(onSavedCallback).not.toHaveBeenCalled();125 expect(result.current.data).toEqual({126 ...loadedData,127 ...defaultArgs.inputAdditionalData,128 uid: defaultArgs.activeUid,129 });130 asyncGetDocument.mockClear();131 /* Update field */132 const editField = 'edit';133 const editValue = 'val';134 act(() => {135 result.current.updateFormData(editField, editValue, true);136 });137 await waitForNextUpdate();138 /* put document is called */139 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {140 ...loadedData,141 ...defaultArgs.inputAdditionalData,142 uid: defaultArgs.activeUid,143 [editField]: editValue,144 });145 /* On save callback called */146 expect(onSavedCallback).toHaveBeenCalledWith(147 defaultArgs.activeUid,148 { ok: true },149 { uid: defaultArgs.activeUid }150 );151 expect(onSavedCallback).toHaveBeenCalledTimes(1);152 expect(asyncGetDocument).not.toHaveBeenCalled();153 /* Final data should be the reloaded data with all other changes claered */154 expect(result.current.data).toEqual({155 ...loadedData,156 ...defaultArgs.inputAdditionalData,157 uid: defaultArgs.activeUid,158 [editField]: editValue,159 });160 });161 test('should update form data and save then reload', async () => {162 const { result, waitForNextUpdate } = renderHook(() =>163 useAsyncObjectManager({ ...defaultArgs, reloadOnSave: true })164 );165 await waitForNextUpdate();166 expect(result.current.data).toEqual({167 ...loadedData,168 ...defaultArgs.inputAdditionalData,169 uid: defaultArgs.activeUid,170 });171 /* We provide alternate load data to show that data is reloaded */172 const altLoadedData = { ...loadedData, altdata: 'altdata' };173 asyncGetDocument.mockClear();174 asyncGetDocument.mockImplementation(async () => altLoadedData);175 /* Update field */176 const editField = 'edit';177 const editValue = 'val';178 act(() => {179 result.current.updateFormData(editField, editValue, true);180 });181 await waitForNextUpdate();182 // /* put document is called */183 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {184 ...loadedData,185 ...defaultArgs.inputAdditionalData,186 uid: defaultArgs.activeUid,187 [editField]: editValue,188 });189 /* On save callback called */190 expect(onSavedCallback).toHaveBeenCalledWith(191 defaultArgs.activeUid,192 { ok: true },193 { uid: defaultArgs.activeUid }194 );195 expect(onSavedCallback).toHaveBeenCalledTimes(1);196 /* We now reload data */197 expect(asyncGetDocument).toHaveBeenCalledWith(198 defaultArgs.collection,199 defaultArgs.activeUid,200 'all',201 'all'202 );203 /* Final data should be the reloaded data with all other changes claered */204 expect(result.current.data).toEqual({205 ...altLoadedData,206 ...defaultArgs.inputAdditionalData,207 uid: defaultArgs.activeUid,208 });209 });210 });...
sendRequest.test.js
Source:sendRequest.test.js
1/*2 Copyright (C) 2021 Edgar Sherman (edgarshermangh14@gmail.com)3 SPDX-License-Identifier: GPL-2.04 This program is free software; you can redistribute it and/or5 modify it under the terms of the GNU General Public License6 version 2 as published by the Free Software Foundation.7 This program is distributed in the hope that it will be useful,8 but WITHOUT ANY WARRANTY; without even the implied warranty of9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10 GNU General Public License for more details.11 You should have received a copy of the GNU General Public License along12 with this program; if not, write to the Free Software Foundation, Inc.,13 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.14*/15import { disableFetchMocks, enableFetchMocks } from "jest-fetch-mock";16import { stringify } from "query-string";17import { setLocalStorage } from "shared/storageHelper";18import { logout } from "shared/authHelper";19import sendRequest from "api/sendRequest";20jest.mock("shared/storageHelper", () => ({21 getLocalStorage: jest.fn(),22 setLocalStorage: jest.fn(),23}));24jest.mock("shared/authHelper", () => ({25 logout: jest.fn(),26}));27describe("sendRequest", () => {28 let defaultArgs;29 beforeEach(() => {30 jest.useFakeTimers();31 enableFetchMocks();32 fetch.doMock();33 defaultArgs = {34 url: "url",35 method: "GET",36 body: null,37 groupName: "myGroupName",38 queryParams: null,39 };40 });41 afterEach(() => {42 disableFetchMocks();43 });44 test("basic call for sendRequest", async () => {45 fetch.mockResponse(JSON.stringify({}));46 await sendRequest(defaultArgs);47 expect(fetch).toHaveBeenCalledWith(48 defaultArgs.url,49 expect.objectContaining({50 body: defaultArgs.body,51 headers: new Headers({52 "content-type": "application/json",53 accept: "application/json",54 groupName: "myGroupName",55 ...defaultArgs.headers,56 }),57 method: defaultArgs.method,58 })59 );60 });61 test("sendRequest handles isMultipart", async () => {62 defaultArgs.method = "POST";63 defaultArgs.body = {};64 defaultArgs.isMultipart = true;65 fetch.mockResponse(JSON.stringify({}));66 await sendRequest(defaultArgs);67 expect(fetch).toHaveBeenCalledWith(68 defaultArgs.url,69 expect.objectContaining({70 body: defaultArgs.body,71 headers: new Headers({72 groupName: "myGroupName",73 ...defaultArgs.headers,74 }),75 method: defaultArgs.method,76 })77 );78 });79 test("sendRequest handles isFile", async () => {80 defaultArgs.isFile = true;81 defaultArgs.method = "POST";82 defaultArgs.body = {};83 fetch.mockResponse(JSON.stringify({}));84 await sendRequest(defaultArgs);85 expect(fetch).toHaveBeenCalledWith(86 defaultArgs.url,87 expect.objectContaining({88 body: JSON.stringify(defaultArgs.body),89 headers: new Headers({90 groupName: "myGroupName",91 ...defaultArgs.headers,92 }),93 method: defaultArgs.method,94 })95 );96 });97 test("sendRequest handles addGroupName", async () => {98 defaultArgs.addGroupName = false;99 fetch.mockResponse(JSON.stringify({}));100 await sendRequest(defaultArgs);101 expect(fetch).toHaveBeenCalledWith(102 defaultArgs.url,103 expect.objectContaining({104 body: defaultArgs.body,105 headers: new Headers({106 "content-type": "application/json",107 accept: "application/json",108 ...defaultArgs.headers,109 }),110 method: defaultArgs.method,111 })112 );113 });114 test("sendRequest handles noHeaders", async () => {115 defaultArgs.noHeaders = true;116 fetch.mockResponse(JSON.stringify({}));117 await sendRequest(defaultArgs);118 expect(fetch).toHaveBeenCalledWith(119 defaultArgs.url,120 expect.objectContaining({121 body: defaultArgs.body,122 headers: {},123 method: defaultArgs.method,124 })125 );126 });127 test("sendRequest handles credentials", async () => {128 defaultArgs.credentials = "user:password";129 fetch.mockResponse(JSON.stringify({}));130 await sendRequest(defaultArgs);131 expect(fetch).toHaveBeenCalledWith(132 defaultArgs.url,133 expect.objectContaining({134 body: defaultArgs.body,135 credentials: defaultArgs.credentials,136 headers: new Headers({137 "content-type": "application/json",138 accept: "application/json",139 groupName: "myGroupName",140 ...defaultArgs.headers,141 }),142 method: defaultArgs.method,143 })144 );145 });146 test("sendRequest handles queryParams", async () => {147 defaultArgs.queryParams = {148 option1: "abc",149 option2: "def",150 };151 fetch.mockResponse(JSON.stringify({}));152 await sendRequest(defaultArgs);153 expect(fetch).toHaveBeenCalledWith(154 `${defaultArgs.url}?${stringify(defaultArgs.queryParams)}`,155 expect.objectContaining({156 body: defaultArgs.body,157 headers: new Headers({158 "content-type": "application/json",159 accept: "application/json",160 groupName: "myGroupName",161 ...defaultArgs.headers,162 }),163 method: defaultArgs.method,164 })165 );166 });167 test("sendRequest handles response headers", async () => {168 const pages = "1";169 const headers = {170 "x-total-pages": pages,171 "Content-Type": "application/json",172 Accept: "*/*",173 };174 const body = { data: {} };175 fetch.mockResponse(JSON.stringify(body), {176 status: 200,177 headers,178 });179 await sendRequest(defaultArgs);180 expect(setLocalStorage).toHaveBeenCalledWith("pages", pages);181 });182 test("sendRequest handles retries", async () => {183 defaultArgs.retries = 3;184 const body = { data: {} };185 fetch.mockResponses(186 [JSON.stringify(body), { status: 400 }],187 [JSON.stringify(body), { status: 200 }]188 );189 await sendRequest(defaultArgs);190 jest.runAllTimers();191 await new Promise((resolve) => setImmediate(resolve));192 jest.runAllTimers();193 expect(fetch).toHaveBeenCalledTimes(2);194 });195 test("sendRequest handles failure", async () => {196 const message = "message";197 const body = { data: {}, message };198 const status = 400;199 fetch.mockResponse(JSON.stringify(body), { status });200 await expect(sendRequest(defaultArgs)).rejects.toEqual(201 expect.objectContaining({202 status,203 ok: false,204 message,205 body,206 })207 );208 });209 test("sendRequest handles 403", async () => {210 const message = "message";211 const status = 403;212 fetch.mockResponses(213 [JSON.stringify({ data: {}, code: status, message }), { status }],214 [JSON.stringify({ data: {}, code: status }), { status }]215 );216 await sendRequest(defaultArgs);217 expect(logout).toHaveBeenCalledWith(218 expect.objectContaining({219 message,220 })221 );222 await sendRequest(defaultArgs);223 expect(logout).toHaveBeenCalledWith(224 expect.objectContaining({225 message: "Requested resource is forbidden",226 })227 );228 });...
AsyncObjectManager.fn.test.js
Source:AsyncObjectManager.fn.test.js
1/* eslint-disable camelcase */2import { renderHook } from '@testing-library/react-hooks';3import useAsycObjectManager from '.';4Date.now = jest.fn().mockImplementation(() => 0);5const loadedData = { loaded: 'data' };6const asyncGetDocument = jest.fn().mockImplementation(async () => loadedData);7const asyncPutDocument = jest.fn().mockImplementation(async () => ({ ok: true }));8const asyncPostDocument = jest.fn().mockImplementation(async () => ({ ok: true }));9const asyncDeleteDocument = jest.fn().mockImplementation(async () => ({ ok: true }));10const onSavedCallback = jest.fn();11const defaultArgs = {12 activeUid: 'demouid',13 collection: 'democollection',14 isNew: false,15 inputAdditionalData: {},16 schema: 'all',17 populate: 'all',18 loadOnInit: true,19 asyncGetDocument,20 asyncPutDocument,21 asyncPostDocument,22 asyncDeleteDocument,23 onSavedCallback,24};25describe('useAsycObjectManager_functional', () => {26 beforeEach(() => {27 asyncGetDocument.mockClear();28 asyncPutDocument.mockClear();29 asyncPostDocument.mockClear();30 asyncDeleteDocument.mockClear();31 onSavedCallback.mockClear();32 });33 test('should call async get docs', async () => {34 const { result, waitForNextUpdate } = renderHook(() => useAsycObjectManager(defaultArgs));35 expect(asyncGetDocument).toHaveBeenCalledWith(36 defaultArgs.collection,37 defaultArgs.activeUid,38 defaultArgs.schema,39 defaultArgs.populate40 );41 expect(result.current.loadedData).toEqual(null);42 expect(result.current.data).toEqual({43 ...defaultArgs.inputAdditionalData,44 uid: defaultArgs.activeUid,45 });46 await waitForNextUpdate();47 expect(result.current.loadedData).toEqual(loadedData);48 expect(result.current.data).toEqual({49 ...loadedData,50 ...defaultArgs.inputAdditionalData,51 uid: defaultArgs.activeUid,52 });53 });54 test('should save data', async () => {55 const { result, waitForNextUpdate } = renderHook(() => useAsycObjectManager(defaultArgs));56 await waitForNextUpdate();57 result.current.saveData();58 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {59 ...loadedData,60 ...defaultArgs.inputAdditionalData,61 uid: defaultArgs.activeUid,62 });63 });64 test('should update form data', async () => {65 const { result, waitForNextUpdate } = renderHook(() => useAsycObjectManager(defaultArgs));66 await waitForNextUpdate();67 expect(result.current.data).toEqual({68 ...loadedData,69 ...defaultArgs.inputAdditionalData,70 uid: defaultArgs.activeUid,71 });72 const editField = 'edit';73 const editValue = 'val';74 result.current.updateFormData(editField, editValue);75 expect(result.current.data).toEqual({76 ...loadedData,77 ...defaultArgs.inputAdditionalData,78 uid: defaultArgs.activeUid,79 [editField]: editValue,80 });81 });82 test('should update form data and save', async () => {83 const { result, waitForNextUpdate } = renderHook(() => useAsycObjectManager(defaultArgs));84 await waitForNextUpdate();85 expect(onSavedCallback).not.toHaveBeenCalled();86 expect(result.current.data).toEqual({87 ...loadedData,88 ...defaultArgs.inputAdditionalData,89 uid: defaultArgs.activeUid,90 });91 asyncGetDocument.mockClear();92 /* Update field */93 const editField = 'edit';94 const editValue = 'val';95 result.current.updateFormData(editField, editValue, true);96 await waitForNextUpdate();97 /* put document is called */98 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {99 ...loadedData,100 ...defaultArgs.inputAdditionalData,101 uid: defaultArgs.activeUid,102 [editField]: editValue,103 });104 /* On save callback called */105 expect(onSavedCallback).toHaveBeenCalledWith(106 defaultArgs.activeUid,107 { ok: true },108 { uid: defaultArgs.activeUid }109 );110 expect(onSavedCallback).toHaveBeenCalledTimes(1);111 expect(asyncGetDocument).not.toHaveBeenCalled();112 /* Final data should be the reloaded data with all other changes claered */113 expect(result.current.data).toEqual({114 ...loadedData,115 ...defaultArgs.inputAdditionalData,116 uid: defaultArgs.activeUid,117 [editField]: editValue,118 });119 });120 test('should update form data and save then reload', async () => {121 const { result, waitForNextUpdate } = renderHook(() =>122 useAsycObjectManager({ ...defaultArgs, reloadOnSave: true })123 );124 await waitForNextUpdate();125 expect(result.current.data).toEqual({126 ...loadedData,127 ...defaultArgs.inputAdditionalData,128 uid: defaultArgs.activeUid,129 });130 /* We provide alternate load data to show that data is reloaded */131 const altLoadedData = { ...loadedData, altdata: 'altdata' };132 asyncGetDocument.mockClear();133 asyncGetDocument.mockImplementation(async () => altLoadedData);134 /* Update field */135 const editField = 'edit';136 const editValue = 'val';137 result.current.updateFormData(editField, editValue, true);138 await waitForNextUpdate();139 /* put document is called */140 expect(asyncPutDocument).toHaveBeenCalledWith(defaultArgs.collection, defaultArgs.activeUid, {141 ...loadedData,142 ...defaultArgs.inputAdditionalData,143 uid: defaultArgs.activeUid,144 [editField]: editValue,145 });146 await waitForNextUpdate();147 /* On save callback called */148 expect(onSavedCallback).toHaveBeenCalledWith(149 defaultArgs.activeUid,150 { ok: true },151 { uid: defaultArgs.activeUid }152 );153 expect(onSavedCallback).toHaveBeenCalledTimes(1);154 /* We now reload data */155 expect(asyncGetDocument).toHaveBeenCalledWith(156 defaultArgs.collection,157 defaultArgs.activeUid,158 'all',159 'all'160 );161 /* Final data should be the reloaded data with all other changes claered */162 expect(result.current.data).toEqual({163 ...altLoadedData,164 ...defaultArgs.inputAdditionalData,165 uid: defaultArgs.activeUid,166 });167 });...
defaultArgs.test.js
Source:defaultArgs.test.js
...8describe('defaultArgs', function () {9 it('should return a key for a integer primary key', function () {10 var Model, args11 Model = sequelize.define('DefaultArgModel', {})12 args = defaultArgs(Model)13 expect(args).to.have.ownProperty('id')14 expect(args.id.type).to.equal(GraphQLInt)15 })16 it('should return a key for a string primary key', function () {17 var Model, args18 Model = sequelize.define('DefaultArgModel', {19 modelId: {20 type: Sequelize.STRING,21 primaryKey: true,22 },23 })24 args = defaultArgs(Model)25 expect(args.modelId.type).to.equal(GraphQLString)26 })27 it('should return a key for a UUID primary key', function () {28 var Model, args29 Model = sequelize.define('DefaultArgModel', {30 uuid: {31 type: Sequelize.UUID,32 primaryKey: true,33 },34 })35 args = defaultArgs(Model)36 expect(args.uuid.type).to.equal(GraphQLString)37 })38 it('should return a key for a UUIDV4 primary key', function () {39 var Model, args40 Model = sequelize.define('DefaultArgModel', {41 uuidv4: {42 type: Sequelize.UUIDV4,43 primaryKey: true,44 },45 })46 args = defaultArgs(Model)47 expect(args.uuidv4.type).to.equal(GraphQLString)48 })49 it('should return multiple keys for a compound primary key', function () {50 var Model, args51 Model = sequelize.define('UserHistory', {52 userId: {53 type: Sequelize.INTEGER,54 primaryKey: true,55 },56 timestamp: {57 type: Sequelize.DATE,58 primaryKey: true,59 },60 })61 args = defaultArgs(Model)62 expect(args.userId.type).to.equal(GraphQLInt)63 expect(args.timestamp.type).to.equal(DateType)64 })65 describe('will have an "where" argument', function () {66 it('that is an GraphQLScalarType', function () {67 var Model, args68 Model = sequelize.define('DefaultArgModel', {69 modelId: {70 type: Sequelize.STRING,71 primaryKey: true,72 },73 })74 args = defaultArgs(Model)75 expect(args).to.have.ownProperty('where')76 expect(args.where.type).to.be.an.instanceOf(GraphQLScalarType)77 })78 })...
updateMyProfile.mutation.js
Source:updateMyProfile.mutation.js
1import { useMutation } from '@apollo/react-hooks';2import gql from 'graphql-tag';3import { useCallback } from 'react';4import * as fragments from '../fragments';5const updateMyProfile = gql `6 mutation UpdateMyProfile(7 $name: String!8 $occupation: String9 $birthDate: DateTime10 $bio: String11 $pictures: [String]!12 ) {13 updateMyProfile(14 name: $name15 occupation: $occupation16 birthDate: $birthDate17 bio: $bio18 pictures: $pictures19 ) {20 ...UserProfile21 }22 }23 ${fragments.user.profile}24`;25updateMyProfile.use = (defaultArgs = {}, defaultOptions = {}) => {26 const queries = require('../queries');27 const { data: { me } = {} } = queries.mine.use();28 const [superMutate, mutation] = useMutation(updateMyProfile, defaultOptions);29 const mutate = useCallback(({30 name = defaultArgs.name,31 birthDate = defaultArgs.birthDate,32 occupation = defaultArgs.occupation,33 bio = defaultArgs.bio,34 pictures = defaultArgs.pictures,35 }) => {36 return superMutate({37 update: (cache, mutation) => {38 if (mutation.error) return;39 fragments.user.profile.write(cache, mutation.data.updateMyProfile);40 },41 variables: { name, birthDate, occupation, bio, pictures },42 });43 }, [44 me,45 superMutate,46 defaultArgs.name,47 defaultArgs.birthDate,48 defaultArgs.occupation,49 defaultArgs.bio,50 defaultArgs.pictures,51 ]);52 return [mutate, mutation];53};...
createUser.mutation.js
Source:createUser.mutation.js
1import { useMutation, useApolloClient } from '@apollo/react-hooks';2import gql from 'graphql-tag';3import { useCallback } from 'react';4const createUser = gql `5 mutation CreateUser(6 $name: String!7 $occupation: String8 $birthDate: DateTime9 $bio: String10 $pictures: [String]!11 ) {12 createUser(13 name: $name14 occupation: $occupation15 birthDate: $birthDate16 bio: $bio17 pictures: $pictures18 )19 }20`;21createUser.use = (defaultArgs = {}, defaultOptions = {}) => {22 const client = useApolloClient();23 const [superMutate, mutation] = useMutation(createUser, defaultOptions);24 const mutate = useCallback(({25 name = defaultArgs.name,26 birthDate = defaultArgs.birthDate,27 occupation = defaultArgs.occupation,28 bio = defaultArgs.bio,29 pictures = defaultArgs.pictures,30 } = {}) => {31 // Token should be stored via response.headers, see graphql/client.js32 return superMutate({33 update: (cache, mutation) => {34 if (mutation.error) return;35 client.clearStore();36 },37 variables: { name, birthDate, occupation, bio, pictures },38 });39 }, [40 superMutate,41 defaultArgs.name,42 defaultArgs.birthDate,43 defaultArgs.occupation,44 defaultArgs.bio,45 defaultArgs.pictures,46 ]);47 return [mutate, mutation];48};...
ProgressBar.stories.jsx
Source:ProgressBar.stories.jsx
1import React from 'react';2import ProgressBar from './ProgressBar';3export default {4 title: 'Components/ProgressBar',5 component: ProgressBar,6};7const Template = (args) => <ProgressBar {...args} />;8const defaultArgs = {9 percentage: 100,10 color: 'primary',11 height: 'small'12}13export const Primary = Template.bind({});14Primary.args = {15 ...defaultArgs16};17export const Secondary = Template.bind({});18Secondary.args = {19 ...defaultArgs,20 color: 'secondary'21};22export const Terciary = Template.bind({});23Terciary.args = {24 ...defaultArgs,25 color: 'terciary'26};27export const Empty = Template.bind({});28Empty.args = {29 ...defaultArgs,30 percentage: 031};32export const Half = Template.bind({});33Half.args = {34 ...defaultArgs,35 percentage: 5036};37export const Full = Template.bind({});38Full.args = {39 ...defaultArgs40};41export const Small = Template.bind({});42Small.args = {43 ...defaultArgs,44 height: 'small'45};46export const Medium = Template.bind({});47Medium.args = {48 ...defaultArgs,49 height: 'medium'50};51export const Large = Template.bind({});52Large.args = {53 ...defaultArgs,54 height: 'large'...
Using AI Code Generation
1var Mocha = require('mocha'),2 fs = require('fs'),3 path = require('path');4var mocha = new Mocha();5var testDir = './test';6fs.readdirSync(testDir).filter(function(file){7 return file.substr(-3) === '.js';8}).forEach(function(file){9 mocha.addFile(10 path.join(testDir, file)11 );12});13mocha.run(function(failures){14 process.on('exit', function () {15 });16});17var assert = require('assert');18describe('Math', function() {19 describe('add', function() {20 it('should return the sum of two numbers', function() {21 assert.equal(2 + 2, 4);22 });23 });24});25var assert = require('assert');26describe('Other', function() {27 describe('add', function() {28 it('should return the sum of two numbers', function() {29 assert.equal(2 + 2, 4);30 });31 });32});33var assert = require('assert');34describe('Another', function() {35 describe('add', function() {36 it('should return the sum of two numbers', function() {37 assert.equal(2 + 2, 4);38 });39 });40});41var assert = require('assert');42describe('Another', function() {43 describe('add', function() {44 it('should return the sum of two numbers', function() {45 assert.equal(2 + 2, 4);46 });47 });48});49var assert = require('assert');50describe('Another', function() {51 describe('add', function() {52 it('should return the sum of two numbers', function() {53 assert.equal(2 + 2, 4);54 });55 });56});57var assert = require('assert');58describe('Another', function() {59 describe('add', function() {60 it('should return
Using AI Code Generation
1const Mocha = require('mocha');2const fs = require('fs');3const path = require('path');4const mocha = new Mocha();5const testDir = './test';6fs.readdirSync(testDir).filter(function(file) {7 return file.substr(-3) === '.js';8}).forEach(function(file) {9 mocha.addFile(10 path.join(testDir, file)11 );12});13mocha.run(function(failures) {14 process.on('exit', function () {15 });16});
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha();3mocha.addFile('test.js');4mocha.run(function(failures){5 process.on('exit', function () {6 });7});8var Mocha = require('mocha');9var mocha = new Mocha();10mocha.addFile('test.js');11mocha.run(function(failures){12 process.on('exit', function () {13 });14});15var Mocha = require('mocha');16var mocha = new Mocha();17mocha.addFile('test.js');18mocha.run(function(failures){19 process.on('exit', function () {20 });21});22var Mocha = require('mocha');23var mocha = new Mocha();24mocha.addFile('test.js');25mocha.run(function(failures){26 process.on('exit', function () {27 });28});29var Mocha = require('mocha');30var mocha = new Mocha();31mocha.addFile('test.js');32mocha.run(function(failures){33 process.on('exit', function () {34 });35});36var Mocha = require('mocha');37var mocha = new Mocha();38mocha.addFile('test.js');39mocha.run(function(failures){40 process.on('exit', function () {41 });42});43var Mocha = require('mocha');44var mocha = new Mocha();45mocha.addFile('test.js');46mocha.run(function(failures){47 process.on('exit', function () {48 process.exit(failures
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha({3});4mocha.addFile('test.js');5mocha.run(function(failures){6 process.on('exit', function () {7 });8});
Using AI Code Generation
1const Mocha = require('mocha');2const mocha = new Mocha();3mocha.addFile('test/test.js');4mocha.defaultArgs();5mocha.run(failures => {6 process.on('exit', () => {7 });8});9mocha.addFile('test/test.js');10mocha.defaultArgs();11mocha.run(failures => {12 process.on('exit', () => {13 });14});
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha();3mocha.addFile('test1.js');4mocha.addFile('test2.js');5mocha.addFile('test3.js');6mocha.defaultArgs();7mocha.run(function(failures){8 process.on('exit', function () {9 });10});11var Mocha = require('mocha');12var mocha = new Mocha();13mocha.addFile('test1.js');14mocha.addFile('test2.js');15mocha.addFile('test3.js');16mocha.defaultArgs();17mocha.run(function(failures){18 process.on('exit', function () {19 });20});21var Mocha = require('mocha');22var mocha = new Mocha();23mocha.addFile('test1.js');24mocha.addFile('test2.js');25mocha.addFile('test3.js');26mocha.defaultArgs();27mocha.run(function(failures){28 process.on('exit', function () {29 });30});31var Mocha = require('mocha');32var mocha = new Mocha();33mocha.addFile('test1.js');34mocha.addFile('test2.js');35mocha.addFile('test3.js');36mocha.defaultArgs();37mocha.run(function(failures){38 process.on('exit', function () {39 });40});
Using AI Code Generation
1const Mocha = require('mocha')2const mocha = new Mocha({3 reporterOptions: {4 }5})6mocha.addFile('./test/test.js')7mocha.run((failures) => {8 process.on('exit', () => {9 })10})11"scripts": {12 }13const assert = require('assert')14const chai = require('chai')15const chaiHttp = require('chai-http')16chai.use(chaiHttp)17describe('Test', function () {18 it('should return 200', function (done) {19 .get('/posts')20 .end((err, res) => {21 expect(res).to.have.status(200)22 done()23 })24 })25})
Using AI Code Generation
1var mocha = require('mocha');2var Mocha = mocha.Mocha;3var mocha = new Mocha();4mocha.useColors(true);5mocha.addFile('test.js');6mocha.run(function () {7 console.log('done');8});9var mocha = require('mocha');10var Mocha = mocha.Mocha;11var mocha = new Mocha();12mocha.useColors(true);13mocha.addFile('test.js');14mocha.run(function () {15 console.log('done');16});
Using AI Code Generation
1var defaultArgs = require('mocha').reporters.Base.list;2var MochaParallelTests = require('mocha-parallel-tests');3var MochaParallelTests = require('mocha-parallel-tests');4var MochaParallelTests = require('mocha-parallel-tests');5var MochaParallelTests = require('mocha-parallel-tests');6var MochaParallelTests = require('mocha-parallel-tests');7var MochaParallelTests = require('mocha-parallel-tests');8var MochaParallelTests = require('mocha-parallel-tests');9var MochaParallelTests = require('mocha-parallel-tests');10var MochaParallelTests = require('mocha-parallel-tests');11var MochaParallelTests = require('mocha-parallel-tests');12MochaParallelTests.prototype.defaultArgs = defaultArgs;13module.exports = MochaParallelTests;
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!!