How to use defaultArgs method in storybook-root

Best JavaScript code snippet using storybook-root

init.test.js

Source:init.test.js Github

copy

Full Screen

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 })...

Full Screen

Full Screen

use-async-object-manager.fn.test.js

Source:use-async-object-manager.fn.test.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

sendRequest.test.js

Source:sendRequest.test.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

AsyncObjectManager.fn.test.js

Source:AsyncObjectManager.fn.test.js Github

copy

Full Screen

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 });...

Full Screen

Full Screen

defaultArgs.test.js

Source:defaultArgs.test.js Github

copy

Full Screen

...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 })...

Full Screen

Full Screen

updateMyProfile.mutation.js

Source:updateMyProfile.mutation.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

createUser.mutation.js

Source:createUser.mutation.js Github

copy

Full Screen

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};...

Full Screen

Full Screen

ProgressBar.stories.jsx

Source:ProgressBar.stories.jsx Github

copy

Full Screen

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'...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root-decorator';2export default {3};4export const MyComponentStory = (args) => (5 <MyComponent {...args} />6);7MyComponentStory.args = {8};9export const MyComponentStory2 = (args) => (10 <MyComponent {...args} />11);12MyComponentStory2.args = {13};14import { MyComponentStory, MyComponentStory2 } from './test';15describe('MyComponent', () => {16 it('should render with myProp set to some value', () => {17 const { getByText } = render(<MyComponentStory />);18 expect(getByText('some value')).toBeInTheDocument();19 });20 it('should render with myProp set to some other value', () => {21 const { getByText } = render(<MyComponentStory2 />);22 expect(getByText('some other value')).toBeInTheDocument();23 });24});25import { defaultArgs } from 'storybook-root-decorator';26export default {27};28export const MyComponentStory = (args) => (29 <MyComponent {...args} />30);31MyComponentStory.args = {32};33import { MyComponentStory } from './test';34describe('MyComponent', () => {35 it('should render with myProp set to some value', () => {36 const { getByText } = render(<MyComponentStory myProp="some value" />);37 expect(getByText('some value')).toBeInTheDocument();38 });39 it('should render with myProp set to some other value', () => {40 const { getByText } = render(<MyComponentStory myProp="some other value" />);41 expect(get

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root-decorator';2export default {3 argTypes: {4 backgroundColor: { control: 'color' },5 },6};7const Template = (args) => <Test {...args} />;8export const Primary = Template.bind({});9Primary.args = {10};11export const Secondary = Template.bind({});12Secondary.args = {13};14export const Large = Template.bind({});15Large.args = {16};17export const Small = Template.bind({});18Small.args = {19};20import { defaultArgs } from 'storybook-root-decorator';21export default {22 argTypes: {23 backgroundColor: { control: 'color' },24 },25};26const Template = (args) => <Test {...args} />;27export const Primary = Template.bind({});28Primary.args = {29};30export const Secondary = Template.bind({});31Secondary.args = {32};33export const Large = Template.bind({});34Large.args = {35};36export const Small = Template.bind({});37Small.args = {38};39import { defaultArgs } from 'storybook-root-decorator';40export default {41 argTypes: {42 backgroundColor: { control: 'color' },43 },44};45const Template = (args) => <Test {...args} />;46export const Primary = Template.bind({});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { defaultArgs } = require('@storybook-root/args');2const { defaultArgs } = require('@storybook-root/args');3const { defaultArgs } = require('@storybook-root/args');4const { defaultArgs } = require('@storybook-root/args');5const { defaultArgs } = require('@storybook-root/args');6const { defaultArgs } = require('@storybook-root/args');7const { defaultArgs } = require('@storybook-root/args');8const { defaultArgs } = require('@storybook-root/args');9const { defaultArgs } = require('@storybook-root/args');10const { defaultArgs } = require('@storybook-root/args');11const { defaultArgs } = require('@storybook-root/args');12const { defaultArgs } = require('@storybook-root/args');13const { defaultArgs } = require('@storybook-root/args');14const { defaultArgs } = require('@storybook-root/args');15const { defaultArgs } = require('@storybook-root/args');16const { defaultArgs } = require('@storybook-root/args');17const { default

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root'2export const MyComponent = () => {3 const args = defaultArgs(MyComponent, { /* optional args */ })4 return <Component {...args} />5}6import { MyComponent } from 'test.js'7export default {8}9const Template = (args) => <MyComponent {...args} />10export const Default = Template.bind({})11Default.args = {12}

Full Screen

Using AI Code Generation

copy

Full Screen

1import {defaultArgs} from 'storybook-root'2export default defaultArgs({3 props: {4 myProp: {5 }6 }7})8import {storiesOf} from '@storybook/vue'9import {defaultArgs} from 'storybook-root'10import MyComponent from './test.js'11storiesOf('MyComponent', module)12 .add('default', () => ({13 components: {MyComponent},14 ...defaultArgs({myProp: 'value'})15 }))16import {storiesOf} from '@storybook/vue'17import {defaultArgs} from 'storybook-root'18import MyComponent from './test.js'19storiesOf('MyComponent', module)20 .add('default', () => ({21 components: {MyComponent},22 ...defaultArgs({myProp: 'value'})23 }))24 .add('default', () => ({25 components: {MyComponent},26 ...defaultArgs({myProp: 'value'})27 }))28 .add('default', () => ({29 components: {MyComponent},30 ...defaultArgs({myProp: 'value'})31 }))32 .add('default', () => ({33 components: {MyComponent},34 ...defaultArgs({myProp: 'value'})35 }))36 .add('default', () => ({37 components: {MyComponent},38 ...defaultArgs({myProp: 'value'})39 }))40import {storiesOf} from '@storybook/vue'41import {defaultArgs} from 'storybook-root'

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root-decorator';2defaultArgs({3});4export default {5};6export const Button = () => {7};8import React from 'react';9import { withRootDecorator } from 'storybook-root-decorator';10export const decorators = [withRootDecorator()];11export const parameters = {12 actions: { argTypesRegex: '^on[A-Z].*' },13};14import React from 'react';15import { withRootDecorator } from 'storybook-root-decorator';16const withCustomDecorator = (Story, context) => {17 return (18 <Story {...context} />19 );20};21export const decorators = [withRootDecorator(), withCustomDecorator];22export const parameters = {23 actions: { argTypesRegex: '^on[A-Z].*' },24};25import React from 'react';26import { withRootDecorator } from 'storybook-root-decorator';27const withCustomDecorator = (Story, context) => {28 return (29 <Story {...context} />30 );31};32export const decorators = [withRootDecorator(), withCustomDecorator];33export const parameters = {34 actions: { argTypesRegex: '^on[A-Z].*' },35};36import React from 'react';37import { withRootDecorator } from 'storybook-root-decorator';38const withCustomDecorator = (Story, context) => {39 return (40 <Story {...context} />41 );42};43export const decorators = [withRootDecorator(), withCustomDecorator];44export const parameters = {45 actions: { argTypesRegex: '^on[A-Z].*' },46};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root';2const args = defaultArgs({3});4import { defaultArgs } from 'storybook-root';5export default {6 args: defaultArgs({7 }),8};9import { defaultArgs } from 'storybook-root';10export default {11 args: defaultArgs({12 }),13};14import { defaultArgs } from 'storybook-root';15export default {16 args: defaultArgs({17 }),18};19import { defaultArgs } from 'storybook-root';20export default {21 args: defaultArgs({22 }),23};24import { defaultArgs } from 'storybook-root';25export default {26 args: defaultArgs({27 }),28 argTypes: {29 backgroundColor: { control: 'color' },30 onClick: { action: 'clicked' },31 },32};33import { defaultArgs } from 'storybook-root';34export default {35 args: defaultArgs({36 }),37 argTypes: {38 backgroundColor: { control: 'color' },39 onClick: { action:

Full Screen

Using AI Code Generation

copy

Full Screen

1import { defaultArgs } from 'storybook-root';2export default defaultArgs({3 argTypes: {4 },5 story: (args) => <MyComponent {...args} />,6});7import { story } from './test';8export default story;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful