"Unexpected digit after hash token" requiring IFC file in React Native - react-native

I'm simply trying to perform a require(./file.ifc) into my application so I can run it with threejs and expo-gl. Although when I require it, I get this error:
error: SyntaxError: /Users/niltonsf/Desktop/Project/codes.nosync/prjs12/src/test2.ifc: Unexpected digit after hash token. (28:0)
26 |
27 | DATA;
> 28 | #1= IFCORGANIZATION($,'Autodesk Revit 2021 (ESP)',$,$,$);
| ^
29 | #5= IFCAPPLICATION(#1,'2021','Autodesk Revit 2021 (ESP)','Revit');
30 | #6= IFCCARTESIANPOINT((0.,0.,0.));
How I'm attempting to load it:
import { IFCLoader } from 'three/examples/jsm/loaders/IFCLoader';
import { Asset } from 'expo-asset';
export function Main() {
const getUrl = async () => {
const filePath = require('./test2.ifc') as any;
const asset = Asset.fromModule(filePath);
};
My metro.config.js with I had to insert .ifc so I don't get an error when requiring it:
const { getDefaultConfig } = require('metro-config');
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig();
return {
transformer: {
babelTransformerPath: require.resolve('react-native-svg-transformer'),
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
resolver: {
assetExts: assetExts.filter((ext) => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg', 'ifc', 'dwg', 'dxf'],
},
};
})();

Related

React is not defined with react-native-svg in React Native

I'm trying to use SVG in my project with react-native-svg and react-native-svg-transformer
, but I'm getting error React is not defined in the SVG file.
These are my configurations
metro.config.js
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts }
} = await getDefaultConfig();
const config1 =
{transformer: {
babelTransformerPath: require.resolve("react-native-svg-transformer")
},
resolver: {
assetExts: assetExts.filter(ext => ext !== "svg"),
sourceExts: [...sourceExts, "svg"]
}}
const config2 ={
transformer: {
// eslint-disable-next-line #typescript-eslint/require-await
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true
}
}),
babelTransformerPath: require.resolve('react-native-typescript-transformer')
}}
return mergeConfig(config1, config2)
})();
declarations.d.ts
declare module "*.svg" {
import React from 'react';
import { SvgProps } from "react-native-svg";
const content: React.FC<SvgProps>;
export default content;
}
I have tried the command yarn start --reset-cache but it didn't work

Test if imported method is called

I'm trying to test if a composable's method is called from my store. Here's what I have:
/stores/ui:
import { defineStore } from 'pinia';
import { useUtils } from '#/composables/utils';
const { sendEvent } = useUtils();
interface State {
tab: string,
}
export const useUIStore = defineStore('ui', {
state: (): State => ({
tab: 'Home',
}),
actions: {
setTab(tabName: string) {
this.tab = tabName;
sendEvent('navigation', `click_${tabName}`);
},
}
})
#/composables/utils:
export function useUtils() {
const sendEvent = (name: string, value: string) => {
// do stuff
};
return {
sendEvent
};
}
And here's my test file:
import { setActivePinia, createPinia } from 'pinia'
import { useUIStore } from '#/stores/ui';
import { useUtils } from '#/composables/utils';
describe('', () => {
let uiStore;
beforeEach(() => {
setActivePinia(createPinia());
uiStore = useUIStore();
})
it('Sets the active tab', () => {
let sendEvent = jest.spyOn(useUtils(), 'sendEvent');
expect(uiStore.tab).toBe('Home');
uiStore.setTab('help');
expect(uiStore.tab).toBe('help');
expect(sendEvent).toHaveBeenCalledTimes(1);
});
})
I've also tried mocking the import:
jest.mock(
'#/composables/utils',
() => {
function useUtils() {
return {
sendEvent: jest.fn(),
}
}
return {
useUtils
};
},
{ virtual: true },
);
import { useUtils } from '#/composables/utils';
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
What's the correct way of adding a spy to sendEvent ?
In your test file - mock the utils:
const mockSendEvent = jest.fn();
jest.mock("#/composables/utils", () => ({
useUtils: () => ({
sendEvent: mockSendEvent,
}),
}));
and then update your test to use the mock:
it('Sets the active tab', () => {
expect(uiStore.tab).toBe('Home');
uiStore.setTab('help');
expect(uiStore.tab).toBe('help');
expect(mockSendEvent).toHaveBeenCalledTimes(1);
});

metro.config.js How to add svg and css transformer?

I'm bad in understanding what's happening in metro.config.js file
I already added svg transformer. Now I need to add css transformer.
I have such metro.config.js file:
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts }
} = await getDefaultConfig();
return {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false
}
}),
babelTransformerPath: require.resolve("react-native-svg-transformer")
},
resolver: {
assetExts: assetExts.filter(ext => ext !== "svg"),
sourceExts: [...sourceExts, "svg"]
}
};
})();
In order to have react-native-css-modules I need to place such content in metro.config.js:
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { sourceExts },
} = await getDefaultConfig();
return {
transformer: {
babelTransformerPath: require.resolve("react-native-css-transformer"),
},
resolver: {
sourceExts: [...sourceExts, "css"],
},
};
})();
But if I just replace the content svg transformer will not work.
How can I combine two metro.config.js files?

Cannot read property state

I try to test this action:
const getGameList = function(context) {
if(context.state.user.id){
let request_body = {
user_id : context.state.user.id
}
axios.post(`api/game_list_of_user`,request_body).then(response => {
context.commit('UpdateGameList',response.data);
}).catch(error => console.log(error));
}
};
My action is to get the list of game for a specific user.
This action has:
as input my user id .
as output my game of list.
My test:
import actions from '#/store/actions'
import state from '#/store/state'
import store from '#/store'
import axios from 'axios'
jest.mock('axios');
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', () => {
const state = { user: {id: 1} };
const mockFunction = jest.fn();
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
axios.post.mockResolvedValue(response);
actions.getGameList({ mockFunction },{ state });
//expect(mockFunction).toHaveBeenCalledTimes(1);
//expect(mockFunction).toHaveBeenCalledWith('UpdateGameList',response.data);
});
test('Error: an error occurred', () => {
const errorMessage = 'Error';
axios.get.mockImplementationOnce(() =>
Promise.reject(new Error(errorMessage))
);
});
});
I declare my state (with my user id).
I declare my expected response
from my request (the game list = response.data).
I use jest.fn() to mock the function. (Should I do that ?)
I got this error:
I want to check:
My request has been called
The response of my request matches with my expected response
My mutation is then called
How can I solve that error?
Edit1: my test
jest.mock('axios');
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', () => {
const context = {
state : {
user: {
id: 1
}
}
};
const mockFunction = jest.fn();
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
axios.post.mockResolvedValue(response);
actions.getGameList({ mockFunction, context });
expect({ mockFunction, context }).toHaveBeenCalledTimes(1);
expect(mockFunction).toHaveBeenCalledWith('UpdateGameList',response.data);
});
test('Error: an error occurred', () => {
const errorMessage = 'Error';
axios.get.mockImplementationOnce(() =>
Promise.reject(new Error(errorMessage))
);
});
});
this is my solution:
import actions from '#/store/actions'
import mutations from '#/store/mutations'
import state from '#/store/state'
import store from '#/store'
import axios from 'axios'
let url = ''
let body = {}
jest.mock("axios", () => ({
post: jest.fn((_url, _body) => {
return new Promise((resolve) => {
url = _url
body = _body
resolve(true)
})
})
}))
//https://medium.com/techfides/a-beginner-friendly-guide-to-unit-testing-the-vue-js-application-28fc049d0c78
//https://www.robinwieruch.de/axios-jest
//https://lmiller1990.github.io/vue-testing-handbook/vuex-actions.html#testing-actions
describe('getGameList', () => {
test('Success: should return the game list of the user and update gameList in the store', async () => {
const context= {
state: {
user: {
id:1
}
},
commit: jest.fn()
}
const response = {
data: [
{ id:1, name:"game_name1" },
{ id:2, name:"game_name2" }
]
};
axios.post.mockResolvedValue(response) //OR axios.post.mockImplementationOnce(() => Promise.resolve(response));
await actions.getGameList(context)
expect(axios.post).toHaveBeenCalledWith("api/game_list_of_user",{"user_id":1});
expect(axios.post).toHaveBeenCalledTimes(1)
expect(context.commit).toHaveBeenCalledWith("UpdateGameList", response.data)
});
test('Error: an error occurred', () => {
const errorMessage = 'Error';
axios.post.mockImplementationOnce(() =>
Promise.reject(new Error(errorMessage))
);
});
});

err in a redux action test

I'm new to Jest testing and moxios. Just trying to write my first async action test. Test dies with this error:
Expected value to equal:
[{"payload": {"checked": true, "followingInfoId": "1"}, "type": "HANDLE_FAVORITE_SUCCESS"}]
Received:
[{"payload": [TypeError: Cannot read property 'getItem' of undefined], "type": "ERROR"}]
Does anyone can tell me where is the problem. I suppose that the moxios response doesn't go to "then"?
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actions from './index';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const store = mockStore();
describe('followings actions', () => {
beforeEach(() => {
moxios.install();
store.clearActions();
});
afterEach(() => {
moxios.uninstall();
});
it('dispatches the HANDLE_FAVORITE_SUCCESS action', () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
payload: {
followingInfoId: '1',
checked: true
}
});
});
const expectedActions = [
{
'type': 'HANDLE_FAVORITE_SUCCESS',
payload: {
followingInfoId: '1',
checked: true
}
}
];
return store.dispatch(actions.handleFavorite()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
});
Here is the action creator:
export const handleFavorite = data => {
return dispatch => {
return followApi.handleFavorite(data).then(payload => {
dispatch({ type: 'HANDLE_FAVORITE_SUCCESS', payload });
}, err => {
dispatch({ type: 'ERROR', payload: err })
});
}
};
Here is the followApi.handleFavorite:
handleFavorite: (data) => {
return new Promise ((resolve, reject) => {
httpServise.patch(`${host}:${port}/followings/handle-favorite`, data).then(
res => {
if (res.data.payload) {
resolve(res.data.payload);
} else reject({status: 401});
}, err => reject(err)
);
});
},
And and a part of the http-servise if needed:
patch: (url, params) => {
return new Promise((resolve, reject) => {
axios(url, {
method: 'PATCH',
headers: getHeaders(),
data: params
}).then(res => {
resolve(res);
}, err => {
reject(err);
});
});
}
If you want to test action creators, you should mock followApi.handleFavorite method rather than axios.
Here is the solution for testing action creators only use jestjs and typescript, You can mock the module manually by yourself.
Folder structure:
.
├── actionCreators.spec.ts
├── actionCreators.ts
├── followApi.ts
└── httpServise.ts
actionCreators.ts:
import followApi from './followApi';
export const handleFavorite = data => {
return dispatch => {
return followApi.handleFavorite(data).then(
payload => {
dispatch({ type: 'HANDLE_FAVORITE_SUCCESS', payload });
},
err => {
dispatch({ type: 'ERROR', payload: err });
}
);
};
};
followApi.ts:
import { httpServise } from './httpServise';
const host = 'http://github.com/mrdulin';
const port = 3000;
const followApi = {
handleFavorite: data => {
return new Promise((resolve, reject) => {
httpServise.patch(`${host}:${port}/followings/handle-favorite`, data).then(
(res: any) => {
if (res.data.payload) {
resolve(res.data.payload);
} else {
reject({ status: 401 });
}
},
err => reject(err)
);
});
}
};
export default followApi;
httpService.ts:
import axios from 'axios';
function getHeaders() {
return {};
}
export const httpServise = {
patch: (url, params) => {
return new Promise((resolve, reject) => {
axios(url, {
method: 'PATCH',
headers: getHeaders(),
data: params
}).then(
res => {
resolve(res);
},
err => {
reject(err);
}
);
});
}
};
actionCreators.spec.ts:
import configureMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import { AnyAction } from 'redux';
import * as actions from './actionCreators';
import followApi from './followApi';
jest.mock('./followApi.ts', () => {
return {
handleFavorite: jest.fn()
};
});
type State = any;
const middlewares = [thunk];
const mockStore = configureMockStore<State, ThunkDispatch<State, undefined, AnyAction>>(middlewares);
const store = mockStore();
describe('followings actions', () => {
beforeEach(() => {
store.clearActions();
jest.resetAllMocks();
});
it('dispatches the HANDLE_FAVORITE_SUCCESS action', () => {
expect.assertions(2);
const mockedHandleFavoritePayload = {
followingInfoId: '1',
checked: true
};
(followApi.handleFavorite as jest.MockedFunction<typeof followApi.handleFavorite>).mockResolvedValueOnce(
mockedHandleFavoritePayload
);
const data = 'jest';
const expectedActions = [
{
type: 'HANDLE_FAVORITE_SUCCESS',
payload: {
followingInfoId: '1',
checked: true
}
}
];
return store.dispatch(actions.handleFavorite(data)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(followApi.handleFavorite).toBeCalledWith(data);
});
});
it('dispatches the ERROR action', () => {
const mockedhHndleFavoriteError = new Error('network error');
(followApi.handleFavorite as jest.MockedFunction<typeof followApi.handleFavorite>).mockRejectedValueOnce(
mockedhHndleFavoriteError
);
const data = 'jest';
const expectedActions = [
{
type: 'ERROR',
payload: mockedhHndleFavoriteError
}
];
return store.dispatch(actions.handleFavorite(data)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
expect(followApi.handleFavorite).toBeCalledWith(data);
});
});
});
Unit test result with 100% coverage report:
PASS src/stackoverflow/52025257/actionCreators.spec.ts (5.95s)
followings actions
✓ dispatches the HANDLE_FAVORITE_SUCCESS action (5ms)
✓ dispatches the ERROR action (2ms)
-------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
actionCreators.ts | 100 | 100 | 100 | 100 | |
-------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 6.87s, estimated 7s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52025257