How to use mockFetchData method in Jest

Best JavaScript code snippet using jest

mockFetch.js

Source: mockFetch.js Github

copy

Full Screen

...88 sim.login.username = username89 sim.login.id = userId90 /​/​ replace privilegeProfile with privileges in order to determine what privilege he has before further fetching info91 const { privilegeProfileId, ...user} = sim.user[userId]92 mockFetchData(timeout, 200, {93 ...user,94 privilegeProfile: sim.privilegeProfile[privilegeProfileId],95 })96 } else {97 mockFetchData(timeout, 404, 'user not found')98 }99 } else {100 mockFetchData(timeout, 401, 'incorrect login password')101 }102 } else if ((method === HTTP.GET) && (url === URL.API_MY_INFO)) {103 /​/​ replace privilegeProfile with privileges in order to determine what privilege he has before further fetching info104 const timeout = sim.USER.DELAY || TIMEOUT.SHORT105 try {106 const { privilegeProfileId, ...user} = sim.user[sim.login.id]107 mockFetchData(timeout, 200, {108 ...user,109 privilegeProfile: sim.privilegeProfile[privilegeProfileId],110 })111 } catch (_) {112 mockFetchData(timeout, 404, 'user not found')113 }114 } else if ((method === HTTP.POST) && (url === URL.API_CHANGE_PASSWORD)) {115 /​/​ change password, response with array of id116 const timeout = sim.USER.DELAY || TIMEOUT.SHORT117 mockFetchData(timeout, 200, [...data.map(i => i.id)])118 } else if ((method === HTTP.POST) && (url === URL.API_RESET_PASSWORD)) {119 const timeout = sim.USER.DELAY || TIMEOUT.SHORT120 mockFetchData(timeout, 200, [...data])121 } else if ((method === HTTP.GET) && (url === URL.API_USER_INFO)) {122 /​/​ simulate getting user info123 const { locationIds, scopeId } = data124 const timeout = sim.USER.DELAY125 if ((Array.isArray(locationIds)) && (typeof scopeId === 'string')) {126 /​/​FIXME, should response with current user's info instead of hard-coded one127 const { user } = sim128 mockFetchData(timeout, 200, {...user})129 } else {130 mockFetchData(timeout, 400, 'invalid request parameter')131 }132 } else if ((method === HTTP.POST) && (url === URL.API_CREATE_USER)) {133 const timeout = sim.USER.DELAY || TIMEOUT.SHORT134 /​/​ grant a random ID number upon success135 data.forEach((user) => { user.id = randomId(100)})136 mockFetchData(timeout, 200, [...data])137 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_USER)) {138 const timeout = sim.USER.DELAY || TIMEOUT.SHORT139 mockFetchData(timeout, 200, [...data])140 } else if ((method === HTTP.POST) && (url === URL.API_DELETE_USER)) {141 const timeout = sim.USER.DELAY || TIMEOUT.SHORT142 mockFetchData(timeout, 200, [...data])143 } else if ((method === HTTP.GET) && (url === URL.API_LOCATION_INFO)) {144 const timeout = sim.LOCATION.DELAY || TIMEOUT.SHORT145 mockFetchData(timeout, 200, [...sim.location])146 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_LOCATION)) {147 const timeout = sim.LOCATION.DELAY || TIMEOUT.SHORT148 mockFetchData(timeout, 200, data.map((location) => {149 const saveNode = (n1) => {150 let result = {...n1}151 if (n1.id.indexOf('loc-') === 0) {152 result.id = `${randomId()}`153 }154 if (Array.isArray(n1.children)) {155 result.children = n1.children.map(n2 => saveNode(n2))156 }157 return result158 }159 return saveNode(location)160 }))161 } else if ((method === HTTP.GET) && (url === URL.API_SCOPE_INFO)) {162 const timeout = sim.SCOPE.DELAY || TIMEOUT.SHORT163 mockFetchData(timeout, 200, [...sim.scope])164 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_SCOPE)) {165 const timeout = sim.SCOPE.DELAY || TIMEOUT.SHORT166 mockFetchData(timeout, 200, data.map((scope) => {167 const saveNode = (n1) => {168 let result = {...n1}169 if (n1.id.indexOf('scope-') === 0) {170 result.id = `${randomId()}`171 }172 if (Array.isArray(n1.children)) {173 result.children = n1.children.map(n2 => saveNode(n2))174 }175 return result176 }177 return saveNode(scope)178 }))179 } else if ((method === HTTP.GET) && (url === URL.API_PRIVILEGE_PROFILE_INFO)) {180 const timeout = sim.PRIVILEGE_PROFILE.DELAY || TIMEOUT.SHORT181 mockFetchData(timeout, 200, {...sim.privilegeProfile})182 } else if ((method === HTTP.POST) && (url === URL.API_CREATE_PRIVILEGE_PROFILE)) {183 const timeout = sim.PRIVILEGE_PROFILE.DELAY || TIMEOUT.SHORT184 /​/​ grant a random ID number upon success185 data.forEach((privilegeProfile) => { privilegeProfile.id = randomId(100)})186 mockFetchData(timeout, 200, [...data])187 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_PRIVILEGE_PROFILE)) {188 const timeout = sim.PRIVILEGE_PROFILE.DELAY || TIMEOUT.SHORT189 mockFetchData(timeout, 200, [...data])190 } else if ((method === HTTP.POST) && (url === URL.API_DELETE_PRIVILEGE_PROFILE)) {191 const timeout = sim.PRIVILEGE_PROFILE.DELAY || TIMEOUT.SHORT192 mockFetchData(timeout, 200, [...data])193 } else if ((method === HTTP.GET) && (url === URL.API_ACCESS_PROFILE_INFO)) {194 const timeout = sim.ACCESS_PROFILE.DELAY || TIMEOUT.SHORT195 mockFetchData(timeout, 200, {...sim.accessProfile})196 } else if ((method === HTTP.POST) && (url === URL.API_CREATE_ACCESS_PROFILE)) {197 const timeout = sim.ACCESS_PROFILE.DELAY || TIMEOUT.SHORT198 /​/​ grant a random ID number upon success199 data.forEach((accessProfile) => { accessProfile.id = randomId(100)})200 mockFetchData(timeout, 200, [...data])201 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_ACCESS_PROFILE)) {202 const timeout = sim.ACCESS_PROFILE.DELAY || TIMEOUT.SHORT203 mockFetchData(timeout, 200, [...data])204 } else if ((method === HTTP.POST) && (url === URL.API_DELETE_ACCESS_PROFILE)) {205 const timeout = sim.ACCESS_PROFILE.DELAY || TIMEOUT.SHORT206 mockFetchData(timeout, 200, [...data])207 } else if ((method === HTTP.GET) && (url === URL.API_KEY_INFO)) {208 const timeout = sim.KEY.DELAY || TIMEOUT.SHORT209 mockFetchData(timeout, 200, {...sim.key})210 } else if ((method === HTTP.POST) && (url === URL.API_REGISTER_KEY)) {211 const timeout = sim.KEY.DELAY || TIMEOUT.SHORT212 const databaseKeyObject = {213 'KA-000011': {214 serialNumber: 'KA-000011',215 type: 'ACCESS',216 name: '',217 locationId: '5099803df3f4948bd2f98301',218 scopeId: '5099803df3f4948bd2f98311',219 holder: 2,220 validPeriod: {221 from: 1577808000,222 to: 1609430399,223 },224 description: '',225 locks: [],226 users: [],227 },228 'KA-000012': {229 serialNumber: 'KA-000012',230 type: 'MANAGEMENT',231 name: '',232 locationId: '5099803df3f4948bd2f98301',233 scopeId: '5099803df3f4948bd2f98311',234 holder: 5,235 validPeriod: {236 from: 1577808000,237 to: 1609430399,238 },239 description: '',240 usage: '',241 },242 }243 const responseKeys = data.map((keySerialNumber) => (databaseKeyObject[keySerialNumber]))244 if (responseKeys.length > 0) {245 mockFetchData(timeout, 200, responseKeys)246 } else {247 mockFetchData(timeout, 400, 'invalid register key')248 }249 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_KEY)) {250 const timeout = sim.KEY.DELAY || TIMEOUT.SHORT251 mockFetchData(timeout, 200, [...data])252 } else if ((method === HTTP.POST) && (url === URL.API_DEREGISTER_KEY)) {253 const timeout = sim.KEY.DELAY || TIMEOUT.SHORT254 mockFetchData(timeout, 200, [...data])255 } else if ((method === HTTP.POST) && (url === URL.API_PROGRAM_KEY)) {256 const timeout = sim.KEY.DELAY || TIMEOUT.SHORT257 const { operation } = data258 switch (operation) {259 case PROGRAM.FACTORY_RESET:260 /​/​ factory reset access or management key, just return the key serial numbers261 break262 default:263 break264 }265 mockFetchData(timeout, 200, {...data})266 } else if ((method === HTTP.GET) && (url === URL.API_KEY_MANAGER_INFO)) {267 const timeout = sim.KEY_MANAGER.DELAY || TIMEOUT.SHORT268 mockFetchData(timeout, 200, {...sim.keyManager})269 } else if ((method === HTTP.POST) && (url === URL.API_REGISTER_KEY_MANAGER)) {270 const timeout = sim.KEY_MANAGER.DELAY || TIMEOUT.SHORT271 const databaseKeyObject = {272 'KMA-000011': {273 ports: [274 'KA-000006',275 'KA-000005',276 undefined,277 undefined,278 ],279 },280 'KMA-000012': {281 ports: [282 undefined,283 'KA-000008',284 undefined,285 undefined,286 ],287 },288 'KMA-000013': {289 ports: [290 undefined,291 undefined,292 undefined,293 undefined,294 ],295 },296 }297 const responseKeyManagers = data.map((keyManager) => ({298 ...keyManager,299 ports: databaseKeyObject[keyManager.serialNumber] && databaseKeyObject[keyManager.serialNumber].ports300 }))301 if (responseKeyManagers.length > 0) {302 mockFetchData(timeout, 200, responseKeyManagers)303 } else {304 mockFetchData(timeout, 400, 'invalid register key manager')305 }306 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_KEY_MANAGER)) {307 const timeout = sim.KEY_MANAGER.DELAY || TIMEOUT.SHORT308 mockFetchData(timeout, 200, [...data])309 } else if ((method === HTTP.POST) && (url === URL.API_DEREGISTER_KEY_MANAGER)) {310 const timeout = sim.KEY_MANAGER.DELAY || TIMEOUT.SHORT311 mockFetchData(timeout, 200, [...data])312 } else if ((method === HTTP.GET) && (url === URL.API_LOCK_INFO)) {313 const timeout = sim.LOCK.DELAY || TIMEOUT.MIDDLE314 mockFetchData(timeout, 200, {...sim.lock})315 } else if ((method === HTTP.POST) && (url === URL.API_REGISTER_LOCK)) {316 const timeout = sim.LOCK.DELAY || TIMEOUT.MIDDLE317 mockFetchData(timeout, 200, [...data])318 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_LOCK)) {319 const timeout = sim.LOCK.DELAY || TIMEOUT.MIDDLE320 mockFetchData(timeout, 200, [...data])321 } else if ((method === HTTP.POST) && (url === URL.API_DEREGISTER_LOCK)) {322 const timeout = sim.LOCK.DELAY || TIMEOUT.MIDDLE323 mockFetchData(timeout, 200, [...data])324 } else if ((method === HTTP.GET) && (url === URL.API_AUTHEN_TOKEN_INFO)) {325 const timeout = sim.AUTHEN_TOKEN.DELAY || TIMEOUT.MIDDLE326 mockFetchData(timeout, 200, {...sim.authenToken})327 } else if ((method === HTTP.POST) && (url === URL.API_REGISTER_AUTHEN_TOKEN)) {328 const timeout = sim.AUTHEN_TOKEN.DELAY || TIMEOUT.MIDDLE329 mockFetchData(timeout, 200, [...data])330 } else if ((method === HTTP.POST) && (url === URL.API_UPDATE_AUTHEN_TOKEN)) {331 const timeout = sim.AUTHEN_TOKEN.DELAY || TIMEOUT.MIDDLE332 mockFetchData(timeout, 200, [...data])333 } else if ((method === HTTP.POST) && (url === URL.API_DEREGISTER_AUTHEN_TOKEN)) {334 const timeout = sim.AUTHEN_TOKEN.DELAY || TIMEOUT.MIDDLE335 mockFetchData(timeout, 200, [...data])336 } else if ((method === HTTP.GET) && (url === URL.API_ACTIVITY)) {337 const timeout = sim.ACTIVITY.DELAY || TIMEOUT.LONG338 /​/​ simulate download rate to max at 7 days per request339 const maxDownloadSeconds = 604800340 const {from, to} = ((data) => (341 (data.descending) ? {342 from: Math.max(data.to - maxDownloadSeconds, data.from),343 to: data.to,344 } : {345 from: data.from,346 to: Math.min(data.from + maxDownloadSeconds, data.to),347 }348 ))(data)349 if (initActivity) {350 /​/​ initial fetchActivity(), response with bulk activity351 mockFetchData(timeout, 200, { ...sim.activity, from, to })352 initActivity = false353 } else {354 /​/​ subsequent getActivity(), response with run-time activity355 const lock = {356 datetime: from,357 userName: 'James Dean',358 description: 'Description: lock activity at ' + from,359 locationId: '5099803df3f4948bd2f98301',360 scopeId: '5099803df3f4948bd2f98311',361 keySerialNumber: 'KA-000001',362 keyName: 'Key KA-000001',363 lockSerialNumber: 'LA-000001',364 lockName: 'Lock LA-000001',365 lockLocationId: '5099803df3f4948bd2f98301',366 lockScopeId: '5099803df3f4948bd2f98311',367 }368 const operation = {369 datetime: from,370 userName: 'Whitney Houston',371 description: 'Description: operation activity at ' + from,372 }373 const system = {374 datetime: from,375 description: 'Description: system activity at ' + from,376 }377 mockFetchData(timeout, 200, { lock: {[from]: lock}, operation: {[from]: operation}, system: {[from]: system}, from, to })378 }379 } else if ((method === HTTP.GET) && (url === URL.API_VERSION)) {380 const timeout = sim.VERSION.DELAY || TIMEOUT.LONG381 const userId = sim.login.id382 if (userId) {383 /​/​ replace privilegeProfile with privileges in order to determine what privilege he has before further fetching info384 const { privilegeProfileId } = sim.user[userId]385 const { privileges } = sim.privilegeProfile[privilegeProfileId]386 const version = {}387 if (privilege.hasUser(privileges)) {388 version.user = 1389 version.privilegeProfile = 1390 }391 if (privilege.hasLocationScope(privileges)) {392 version.location = 1393 version.scope = 1394 }395 if (privilege.hasAccessProfile(privileges)) {396 version.accessProfile = 1397 }398 if (privilege.hasAccessResources(privileges)) {399 version.key = 1400 }401 if (privilege.hasManagementResources(privileges)) {402 version.keyManager = 1403 version.lock = 1404 version.authenToken = 1405 }406 mockFetchData(timeout, 200, {version})407 } else {408 mockFetchData(timeout, 404, 'user not found')409 }410 } else {411 /​/​ restore default fetch412 window.fetch = fetch413 }414}...

Full Screen

Full Screen

VideoDetailpage.test.js

Source: VideoDetailpage.test.js Github

copy

Full Screen

1import React from 'react'2import { shallow } from 'enzyme'3import configureMockStore from 'redux-mock-store'4import thunk from 'redux-thunk'5import { VideoDetailPage, mapStateToProps, loadData } from '../​../​src/​scripts/​pages/​VideoDetailpage'6import fetchTrendings from '../​../​src/​scripts/​actions/​fetch-trendings'7import fetchVideoDetail from '../​../​src/​scripts/​actions/​fetch-video-detail'8const createMockStore = configureMockStore([thunk])9describe('Video Detail Page', () => {10 const setup = (propOverrides) => {11 const state = {12 videoDetail: {13 isFetching: false,14 error: null,15 video: {16 id: 'lZoA5ZX4wC0',17 title: 'Ocean Beach Surfing Raw | San…cisco, CA',18 channelTitle: 'Jeff Chavolla',19 viewCount: '121034',20 publishedAt: '2017-12-04T07:18:50.000Z',21 description: 'Raw surfing video clips of Ocean Beach in San Francisco',22 thumbnail: {23 url: 'https:/​/​i.ytimg.com/​vi/​lZoA5ZX4wC0/​hqdefault.jpg',24 width: 480,25 height: 36026 }27 }28 },29 trendings: {30 isFetching: false,31 videos: [32 {33 id: 'lZoA5ZX4wC0',34 title: 'Video Title',35 description: 'Lorem ipsum dolor sit amed.',36 thubmnail: 'video-thumbnail.jpg'37 },38 {39 id: 'lZoA5ZX4wC01',40 title: 'Video Title 2',41 description: 'Lorem ipsum dolor sit amed.',42 thubmnail: 'video-thumbnail-2.jpg'43 }44 ]45 }46 }47 const store = createMockStore(state)48 const props = {49 videoDetail: state.videoDetail,50 trendings: state.trendings,51 history: {52 push: jest.fn()53 },54 match: {55 params: { id: 'lZoA5ZX4wC0' }56 },57 fetchVideoDetail: jest.fn(),58 fetchTrendings: jest.fn(),59 ...propOverrides60 }61 const nextProps = { match: { params: { id: 'lZoA5ZX4wC01' } } }62 const wrapper = shallow(<VideoDetailPage {...props} /​>)63 return {64 wrapper,65 props,66 nextProps,67 store,68 state69 }70 }71 it('renders properly', () => {72 const { wrapper } = setup()73 expect(wrapper).toMatchSnapshot()74 })75 describe('componentDidMount call', () => {76 it('calls fetchVideoDetail action when first page load', () => {77 const { wrapper, props } = setup({ videoDetail: { isFetching: true, video: {} } })78 const mockFetchData = jest.spyOn(VideoDetailPage.prototype, 'fetchData')79 wrapper.instance().componentDidMount()80 expect(wrapper).toMatchSnapshot()81 expect(mockFetchData).toHaveBeenCalledWith(props.match.params.id)82 })83 it('calls fetchVideoDetail action if video id is not equal to match params id', () => {84 const { wrapper, props } = setup()85 const mockFetchData = jest.spyOn(VideoDetailPage.prototype, 'fetchData')86 wrapper.instance().componentDidMount()87 expect(mockFetchData).toHaveBeenCalledWith(props.match.params.id)88 })89 })90 describe('componentWillReceiveProps call', () => {91 it('calls fetchVideoDetail when page doesn\'t changed.', () => {92 const { wrapper, props } = setup()93 const mockFetchData = jest.spyOn(VideoDetailPage.prototype, 'fetchData')94 wrapper.instance().componentWillReceiveProps(props)95 expect(wrapper).toMatchSnapshot()96 expect(mockFetchData.mock.calls).toHaveLength(1)97 })98 it('calls fetchVideoDetail when page changed.', () => {99 const { wrapper, nextProps } = setup()100 const mockFetchData = jest.spyOn(VideoDetailPage.prototype, 'fetchData')101 wrapper.instance().componentWillReceiveProps(nextProps)102 expect(wrapper).toMatchSnapshot()103 expect(mockFetchData.mock.calls).toHaveLength(2)104 })105 })106 it('returns videoDetail object when initialize component', () => {107 const { props } = setup()108 expect(mapStateToProps(props).videoDetail).toEqual(props.videoDetail)109 })110 it('checks loadData function', () => {111 const { store, props } = setup()112 expect(loadData(store, props.match)).toEqual(Promise.all([ store.dispatch(fetchVideoDetail(props.match.params.id)), store.dispatch(fetchTrendings()) ]))113 })...

Full Screen

Full Screen

UserList.test.js

Source: UserList.test.js Github

copy

Full Screen

1import React from 'react';2/​/​ import { shallow } from 'enzyme';3import { MemoryRouter } from 'react-router-dom';4import UserList from '../​../​../​user/​components/​UserList';5/​/​ https:/​/​stackoverflow.com/​questions/​58117890/​how-to-test-components-using-new-react-router-hooks6jest.mock('react-router-dom', () => ({7 ...jest.requireActual('react-router-dom'), /​/​ use actual for all non-hook parts8 useRouteMatch: () => ({url: '/​users'}),9}));10describe.skip('UserList', () => {11 let wrapper;12 let userList;13 let useEffect;14 let mockedUserData;15 let mockFetchData = jest.fn().mockResolvedValue();16 let props = {fetchData: mockFetchData};17 const mockUseEffect = () => {18 useEffect.mockImplementationOnce((f) => f());19 };20 beforeEach(() => {21 useEffect = jest.spyOn(React, 'useEffect');22 mockUseEffect();23 wrapper = shallow(<MemoryRouter><UserList {...props} /​></​MemoryRouter>);24 userList = wrapper.find(UserList).dive();25 });26 it('renders correctly', () => {27 expect(userList).toMatchSnapshot();28 });29 describe('when mounted', () => {30 beforeEach(() => {31 mockFetchData = jest.fn();32 props = {fetchData: mockFetchData};33 mockUseEffect();34 wrapper = shallow(<MemoryRouter><UserList {...props} /​></​MemoryRouter>);35 userList = wrapper.find(UserList).dive();36 });37 it('calls "fetchData" method', () => {38 expect(props.fetchData).toHaveBeenCalled();39 });40 describe('contains valid user data', () => {41 beforeEach(() => {42 mockedUserData = [43 {id: 1, username: 'admin'},44 {id: 2, username: 'bob'},45 ];46 mockFetchData = jest.fn().mockResolvedValue(mockedUserData);47 props = {fetchData: mockFetchData};48 mockUseEffect();49 wrapper = shallow(<MemoryRouter><UserList {...props} /​></​MemoryRouter>);50 userList = wrapper.find(UserList).dive();51 });52 it('displays each users username', () => {53 const usernameElements = userList.find('.user-list-username');54 expect(usernameElements.length).toEqual(mockedUserData.length);55 for (const n in usernameElements.getElements()) {56 expect(usernameElements.at(n).text()).toEqual(mockedUserData[n].username);57 }58 });59 });60 describe('contains invalid user data', () => {61 beforeEach(() => {62 mockedUserData = {detail: 'Authentication credentials were not provided'};63 mockFetchData = jest.fn().mockResolvedValue(mockedUserData);64 props = {fetchData: mockFetchData};65 mockUseEffect();66 wrapper = shallow(<MemoryRouter><UserList {...props} /​></​MemoryRouter>);67 userList = wrapper.find(UserList).dive();68 });69 it('shows error message', () => {70 const usernameElements = userList.find('.user-list-username');71 expect(usernameElements.length).toEqual(0);72 const errorMessage = userList.find('.user-list-errors');73 expect(errorMessage.text()).toEqual(mockedUserData.detail);74 });75 });76 });...

Full Screen

Full Screen

project-repository.spec.js

Source: project-repository.spec.js Github

copy

Full Screen

...18 const projects = [19 { name: 'awesome-project' },20 { name: 'pet-project' }21 ]22 mockFetchData(projects)23 const result = await ProjectRepository.get()24 expect(global.fetch).toHaveBeenCalledTimes(1)25 expect(result).toEqual(projects)26 })27 it('correctly get relative docs path', () => {28 const [project, version, expectedPath] = ['project', '1.0', 'index.html']29 const absoluteDocsPath = `https:/​/​do.cat/​doc/​${project}/​${version}/​${expectedPath}`30 const relativeDocsPath = ProjectRepository.getDocsPath('project', '1.0', absoluteDocsPath)31 expect(relativeDocsPath).toEqual(expectedPath)32 })33 it('should get all versions of a project', async () => {34 const versions = [35 { name: '1.0', type: 'directory' },36 { name: '2.0', type: 'directory' },37 { name: 'image.png', type: 'file' }38 ]39 mockFetchData(versions)40 const result = await ProjectRepository.getVersions('awesome--project')41 expect(global.fetch).toHaveBeenCalledTimes(1)42 expect(result).toEqual(versions.filter((version) => version.type == 'directory'))43 })44 it('should upload new documentation', async () => {45 mockFetchData({})46 await ProjectRepository.upload('awesome-project', '4.0', { data: true })47 expect(global.fetch).toHaveBeenCalledTimes(1)48 expect(global.fetch).toHaveBeenCalledWith('https:/​/​do.cat/​api/​awesome-project/​4.0',49 {50 'body': { 'data': true },51 'method': 'POST'52 }53 )54 })55 it('should delete an existing documentation', async () => {56 mockFetchData({})57 await ProjectRepository.delete_doc('awesome-project', '1.2', '1234')58 expect(global.fetch).toHaveBeenCalledTimes(1)59 expect(global.fetch).toHaveBeenCalledWith('https:/​/​do.cat/​api/​awesome-project/​1.2',60 {61 'method': 'DELETE',62 'headers': { 'Docat-Api-Key': '1234' }63 }64 )65 })...

Full Screen

Full Screen

App.test.js

Source: App.test.js Github

copy

Full Screen

1import { shallow } from 'enzyme';2import Profile from './​components/​Profile';3import Loader from './​components/​Loader';4import ErrorHandler from './​components/​ErrorHandler';5import App from './​App.js';6import useFetch from './​hooks/​useFetch';7import mockUser from './​__mocks__/​user';8const mockFetchData = jest.fn();9const mockError = new Error('User is not found');10jest.mock('./​hooks/​useFetch.js', () => jest.fn());11describe('Test App.js', () => {12 beforeEach(() => {13 useFetch.mockImplementation(() => ({14 response : null,15 error : null,16 loading : false,17 fetchData : mockFetchData18 }));19 });20 it('Should render a Profile component', () => {21 useFetch.mockImplementation(() => ({ response: mockUser }));22 const wrapper = shallow(<App /​>);23 expect(wrapper.find(Profile)).toHaveLength(1);24 expect(wrapper.find(Profile).props().data).toBe(mockUser.results[0]);25 });26 it('Should trigger fetchData if loading is false', () => {27 const wrapper = shallow(<App /​>);28 wrapper.find('button').simulate('click');29 expect(mockFetchData).toHaveBeenCalledTimes(1);30 });31 it('Shouldn\'t trigger fetchData if loading is true', () => {32 useFetch.mockImplementation(() => ({ loading: true }));33 const wrapper = shallow(<App /​>);34 wrapper.find('button').simulate('click');35 expect(mockFetchData).toHaveBeenCalledTimes(0);36 });37 it('Should render a Loading component', () => {38 useFetch.mockImplementation(() => ({ loading: true }));39 const wrapper = shallow(<App /​>);40 expect(wrapper.find(Loader)).toHaveLength(1);41 });42 it('Should render a ErrorHandler component', () => {43 useFetch.mockImplementation(() => ({ error: mockError }));44 const wrapper = shallow(<App /​>);45 expect(wrapper.find(ErrorHandler)).toHaveLength(1);46 expect(wrapper.find(ErrorHandler).props().error).toBe(mockError);47 });...

Full Screen

Full Screen

fetch.es.js

Source: fetch.es.js Github

copy

Full Screen

1/​**2 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.3 *4 * The contents of this file are subject to the terms of the Liferay Enterprise5 * Subscription License ("License"). You may not use this file except in6 * compliance with the License. You can obtain a copy of the License by7 * contacting Liferay, Inc. See the License for the specific language governing8 * permissions and limitations under the License, including but not limited to9 * distribution rights of the Software.10 */​11const globalFetch = global.fetch;12const fetchMockResponse = async (response, ok = true) => ({13 json: async () => response,14 ok,15 text: async () => response,16});17function FetchMock(mockDatas = {}) {18 this.mock = () => {19 global.fetch = jest.fn(async (url, {method}) => {20 const mockFetchData = mockDatas[method][url.pathname || url];21 if (mockFetchData) {22 if (Array.isArray(mockFetchData)) {23 if (mockFetchData.length) {24 if (mockFetchData.length === 1) {25 if (mockFetchData[0]) {26 return await mockFetchData[0];27 }28 }29 else {30 return await mockFetchData.shift();31 }32 }33 }34 else {35 return await mockFetchData;36 }37 }38 const mockDataDefault = mockDatas[method].default;39 if (mockDataDefault) {40 if (Array.isArray(mockDataDefault)) {41 if (mockDataDefault.length) {42 if (mockDataDefault.length === 1) {43 if (mockDataDefault[0]) {44 return await mockDataDefault[0];45 }46 }47 else {48 return await mockDataDefault.shift();49 }50 }51 }52 else {53 return await mockDataDefault;54 }55 }56 throw new Error(57 `Request not mocked - method: ${method} - URL: ${58 url.pathname || url59 }`60 );61 });62 };63 this.reset = () => {64 global.fetch = globalFetch;65 };66 this.reset();67 this.mock();68}69export {fetchMockResponse};...

Full Screen

Full Screen

omdb.test.js

Source: omdb.test.js Github

copy

Full Screen

1const mockFetchData = jest.fn();2const mockHttp = {3 fetchData: mockFetchData,4};5jest.mock("../​../​app/​services/​http", () => mockHttp);6const { Movies } = require("../​../​app/​services/​omdb");7describe("Test OMDB API", () => {8 beforeEach(() => {9 jest.clearAllMocks();10 });11 afterEach(() => {12 jest.clearAllMocks();13 });14 test("Checking parameters creation", async () => {15 const attrs = [16 { attr: "i", value: "movieid123" },17 { attr: "type", value: "movie" }];18 expect.assertions(2);19 mockFetchData.mockImplementationOnce((params) => {20 const res = { data: [] };21 expect(params).toEqual("&i=movieid123&type=movie");22 return Promise.resolve(res);23 });24 Movies.getMovies(attrs);25 expect(mockFetchData).toBeCalled();26 });...

Full Screen

Full Screen

NoContent.test.js

Source: NoContent.test.js Github

copy

Full Screen

1import React from 'react';2import { shallow } from 'enzyme';3import renderer from 'react-test-renderer';4import NoContent from '../​components/​NoContent';5describe('NoContent', () => {6 const mockFetchData = jest.fn();7 const component = <NoContent fetchData={mockFetchData} /​>;8 const sComponent = shallow(component);9 it('renders and matches our snapshot', () => {10 const rComponent = renderer.create(component);11 const tree = rComponent.toJSON();12 expect(tree).toMatchSnapshot();13 });14 it('calls the passed in fetchData function when the try again button is clicked', () => {15 sComponent.find('.no-content__button').simulate('click');16 expect(mockFetchData).toBeCalled();17 });...

Full Screen

Full Screen

StackOverFlow community discussions

Questions
Discussion

React Native: How to test if element is focused?

eslint throws `no-undef` errors when linting Jest test files

High Jest Heap Memory Usage in JavaScript React Projects

How to exclude CSS module files from jest test suites?

Eslint doesn&#39;t work in VScode, but work from terminal

Module build failed , vue-router.esm.js in Vue js

How to use Jest with jsdom to test console.log?

Message &quot;Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout&quot;

How to overwrite (or mock) a class method with Jest in order to test a function?

Specify code to run before any Jest setup happens

Sunk several hours in to this today. From what I can see, React Native Testing Library doesn't have this matcher and neither does the Jest Native matcher extender.

It looks like Detox supports it though.

There are lots of suggestions to use refs (which might let us call ref.current.isFocused()), or capture onFocus\onBlur events. But these aren't viable from the test environment perspective.

There were 2 things I observed with the refs.

  1. The refs all get mocked out in jest (I don't know enough about jest to know why).
  2. When the element is not focused, the ref is completely gone

Regarding, tracking onFocus\onBlur, it's unnecessary overhead and only further complicates the production code for the sake of testing. Then the component has to accept these as props and a mock has to be created for each one... no thanks!

I decided to open a feature request in the Jest Native project. Cross your fingers.

React.js users have it so easy!

https://stackoverflow.com/questions/65890013/react-native-how-to-test-if-element-is-focused

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Run Cypress Tests In Jenkins Pipeline [Jenkins and Cypress Tutorial]

Cypress is one of the fast-growing test automation frameworks. As you learn Cypress, you will probably come across the need to integrate your Cypress tests with your CI environment. Jenkins is an open-source Continuous Integration (CI) server that automates your web applications’ build and deploys process. By running your Cypress test suite in Jenkins, you also automate testing as part of the build process.

Top 7 Programming Languages For Test Automation In 2020

So you are at the beginning of 2020 and probably have committed a new year resolution as a tester to take a leap from Manual Testing To Automation . However, to automate your test scripts you need to get your hands dirty on a programming language and that is where you are stuck! Or you are already proficient in automation testing through a single programming language and are thinking about venturing into new programming languages for automation testing, along with their respective frameworks. You are bound to be confused about picking your next milestone. After all, there are numerous programming languages to choose from.

A Comprehensive Guide To Storybook Testing

Storybook offers a clean-room setting for isolating component testing. No matter how complex a component is, stories make it simple to explore it in all of its permutations. Before we discuss the Storybook testing in any browser, let us try and understand the fundamentals related to the Storybook framework and how it simplifies how we build UI components.

13 Best JavaScript Frameworks For 2020

According to stackoverflow’s developer survey 2020, JavaScript is the most commonly used language for the 8th year straight with 67.7% people opting for it. The major reason for its popularity is the fact that JavaScript is versatile and can be used for both frontend and backend development as well as for testing websites or web applications as well.

19 Best Practices For Automation testing With Node.js

Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

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

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

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

Run Jest automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful