Jest coverage in redux reducer - object destruction not covered - ecmascript-6

I have the following issue with Jest:
I have this reducer:
[REMOVE_FILTER]: (state: FiltersState, action: Action<string>): FiltersState => {
const { [action.payload!]: deleted, ...activeFilters } = state.activeFilters;
return { ...state, activeFilters, createFilterSelection: undefined, filterCreateOpen: false };
}
When I am trying to test it, it says that I do not have coverage for
...activeFilters } = state.activeFilters;
Here is my test:
test(REMOVE_FILTER, () => {
const action: IAction<string> = {
type: REMOVE_FILTER,
payload: "subprovider"
};
expect(
testReducer({ reducer, state, action })
).toEqual({
...state,
activeFilters: { name: null, branded: null },
createFilterSelection: undefined,
filterCreateOpen: false
});
});
Can someone suggest what I am doing wrong?
I am using:
Jest 23.6.0
Typescript 3.4.0
Redux 4.0.0
React-Redux: 6.0.0
Redux Actions: 2.6.1
Thank you!
P.S: Here is the Jest config:
{
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"globals": {
"window": true,
"document": true
},
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__test__/.*)\\.test\\.(ts|tsx)$",
"notify": true,
"collectCoverageFrom": [
"**/*.{ts,tsx}"
],
"coveragePathIgnorePatterns": [
"(/__e2e__/.*)",
"(/__specs__/.*)",
"(/__test__/.*)",
"(/interfaces/.*)",
"(index.ts)",
"(src/server/app.ts)",
"(src/server/config.ts)",
"(/mock/.*)",
"(data/mock.ts)",
"(automapperConfiguration.ts)",
"(src/app/store/store.ts)",
"(src/app/containers/brand-configuration/.*)"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"setupTestFrameworkScriptFile": "<rootDir>/jestSetup.js",
"testURL": "http://localhost/"
}
The above TS code gets transpilled to:
[REMOVE_FILTER]: (state, action) => {
const _a = state.activeFilters, _b = action.payload, deleted = _a[_b], activeFilters = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
return Object.assign({}, state, { activeFilters, createFilterSelection: undefined, filterCreateOpen: false });
}

Related

MV3 declarativeNetRequest and X-Frame-Options DENY

I have a MV2 extension with chrome.webRequest that works perfectly but fail on MV3 declarativeNetRequest getting around iframes.
The extension is like a multi-messenger that opens multiple iframes for various sites to merge in a single extension all popular messengers.
So I have a domain "example.com" and there I open multiple iframes, for example open an iframe with Twitter.com or Telegram.org.
Since twitter.com or telegram.org set the X-Frame-Options to DENY those iframes don't show anything.
With MV2 we could run chrome.webRequest and remove those headers:
chrome.webRequest.onHeadersReceived.addListener(
function (details)
{
if (details.tabId && (details.tabId === tabId || details.tabId === -1 || tabMultiId.includes(details.tabId))) {
var b = details.responseHeaders.filter((details) => !['x-frame-options', 'content-security-policy', 'x-content-security-policy', 'strict-transport-security', 'frame-ancestors'].includes(details.name.toLowerCase()));
b.forEach(function(e){
"set-cookie" === e.name && -1 !== e.value.indexOf("Secure") && (-1 !== e.value.indexOf("SameSite=Strict") ?
(e.value = e.value.replace(/SameSite=Strict/g, "SameSite=None"))
: -1 !== e.value.indexOf("SameSite=Lax")
? (e.value = e.value.replace(/SameSite=Lax/g, "SameSite=None"))
: (e.value = e.value.replace(/; Secure/g, "; SameSite=None; Secure")));
});
return {
responseHeaders: b
}
}
},
{
urls: [ "<all_urls>" ],
tabId: tabId
},
["blocking", "responseHeaders", "extraHeaders"]
);
I have tried to do exactly the same with MV3 but keep failing.
My 2 attemps:
async function NetRequest() {
var blockUrls = ["*://*.twitter.com/*","*://*.telegram.org/*"];
var tabId = await getObjectFromLocalStorage('tabId');
var tabMultiId = [];
tabMultiId = JSON.parse(await getObjectFromLocalStorage('tabMultiId'));
tabMultiId.push(tabId);
blockUrls.forEach((domain, index) => {
let id = index + 1;
chrome.declarativeNetRequest.updateSessionRules({
addRules:[
{
"id": id,
"priority": 1,
"action": { "type": "modifyHeaders",
"responseHeaders": [
{ "header": "X-Frame-Options", "operation": "remove" },
{ "header": "Frame-Options", "operation": "remove" },
{ "header": "content-security-policy", "operation": "remove" },
{ "header": "content-security-policy-report-only", "operation": "remove" },
{ "header": "x-content-security-policy", "operation": "remove" },
{ "header": "strict-transport-security", "operation": "remove" },
{ "header": "frame-ancestors", "operation": "remove" },
{ "header": "set-cookie", "operation": "set", "value": "SameSite=None; Secure" }
]
},
"condition": {"urlFilter": domain, "resourceTypes": ["image","media","main_frame","sub_frame","stylesheet","script","font","xmlhttprequest","ping","websocket","other"],
"tabIds" : tabMultiId }
}
],
removeRuleIds: [id]
});
});
}
async function launchWindow(newURL, windowDimensions, urlWindow, isIncognitoWindow, windowType) {
chrome.windows.create({ url: newURL, type: windowType, incognito: isIncognitoWindow, width: windowDimensions.width, height: windowDimensions.height, left: windowDimensions.left, top: windowDimensions.top },
async function (chromeWindow) {
if (urlWindow != "install" || urlWindow != "update") {
chrome.storage.local.set({ 'extensionWindowId': chromeWindow.id }, function () { });
chrome.storage.local.set({ 'tabId': chromeWindow.tabs[0].id }, function () { });
NetRequest();
}
});
}
Also tried:
const iframeHosts = [
'twitter.com', 'telegram.org'
];
const RULE = {
id: 1,
condition: {
initiatorDomains: ['example.com'],
requestDomains: iframeHosts,
resourceTypes: ['sub_frame', 'main_frame'],
},
action: {
type: 'modifyHeaders',
responseHeaders: [
{header: 'X-Frame-Options', operation: 'remove'},
{header: 'Frame-Options', operation: 'remove'},
],
},
};
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [RULE.id],
addRules: [RULE],
});
Permissions:
"permissions": [
"system.display",
"scripting",
"activeTab",
"notifications",
"contextMenus",
"unlimitedStorage",
"storage",
"declarativeNetRequestWithHostAccess",
"webNavigation",
"alarms"
],
"host_permissions": [
"<all_urls>"
],
Any of this attempts worked.
Greetings and thank you very much for anyone that try to help.
You need to unregister service worker for the site and clear its cache using chrome.browsingData API.
Syntax for urlFilter is different, so your "*://*.twitter.com/*" is incorrect and should be "||twitter.com/", however a better solution is to use requestDomains because it allows specifying multiple sites in just one rule.
// manifest.json
"permissions": ["browsingData", "declarativeNetRequest"],
"host_permissions": ["*://*.twitter.com/", "*://*.telegram.org/"],
// extension script
async function configureNetRequest(tabId) {
const domains = [
'twitter.com',
'telegram.org',
];
const headers = [
'X-Frame-Options',
'Frame-Options',
];
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [1],
addRules: [{
id: 1,
action: {
type: 'modifyHeaders',
responseHeaders: headers.map(h => ({ header: h, operation: 'remove'})),
},
condition: {
requestDomains: domains,
resourceTypes: ['sub_frame'],
tabIds: [tabId],
},
}],
});
await chrome.browsingData.remove({
origins: domains.map(d => `https://${d}`),
}, {
cacheStorage: true,
serviceWorkers: true,
});
}
// Usage
chrome.windows.create({ url: 'about:blank' }, async w => {
await configureNetRequest(w.tabs[0].id);
await chrome.tabs.update(w.tabs[0].id, { url: 'https://some.real.url/' });
});

Unable to populate json to FormArray. TypeError: data.map is not a function

I am receiving this json format from api and need to populate it into FormArray. But am getting TypeError: data.map is not a function. Below is the code snippet.
{
"data": [
{
"id": "ASR4324368",
"name": "TTTTT",
"amount": 100
},
{
"id": "GTH435435435",
"name": "AAAAA",
"amount": 500
}
]
}
getProductJson() {
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.subscribe(
(data: any[]) => {
this.productForm = this.fb.group({
product: this.fb.array(
data.map(datum => this.generateDatumFormGroup(datum))
)
});
},
error => {
console.log(error);
}
);
}
private generateDatumFormGroup(datum) {
return this.fb.group({
id: this.fb.control({ value: datum.id, disabled: false }),
productName: this.fb.control({ value: datum.name, disabled: false }),
productAmt: this.fb.control({ value: datum.amount, disabled: false }),
});
}
are you sure you get data? to check use pipe(tap)
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.pipe(tap(res=>{console.log(res)})) //<--add this line
.subscribe(....rest-of your code...)
NOTE: I feel strange your request (but really I don't know if is ok) I ususally use some like
this.httpClient.get('http://myapi/api/controller/action', { withCredentials: true })
Modified to the below and was working.
getProductJson() {
this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
.subscribe(
(data: any[]) => {
this.raw = data;
this.productObj = this.raw.data;
this.productForm = this.fb.group({
product: this.fb.array(
this.productObj.map(datum => this.generateDatumFormGroup(datum))
)
});
},
error => {
console.log(error);
}
);
}

GraphQL - operating elements of array

I would like to display some information about members, but I don't know how to resolve array of field 'time'. This is array, because it shows their login time. What should I do?
I used GraphQLString, but I am aware of this bad solution.
So I'm getting an error:
"message": "String cannot represent value: [\"12:08\"]",
Here is schema.js
const axios = require("axios");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLSchema
} = require("graphql");
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: GraphQLString
}
})
});
//Root Query
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
users: {
type: new GraphQLList(memberType),
description: "List of members",
resolve(parent, args) {
return axios
.get("http://25.98.140.121:5000/data")
.then(res => res.data);
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
});
And here is JSON
[
{
"time": [
"12:08"
],
"nick": "Cogi12",
"name_and_surname: "John Steps"
},
{
"time": [
"12:16"
],
"nick": "haris22",
"name_and_surname": "Kenny Jobs"
},
{
"time": [
"12:07",
"12:08",
"12:17",
"12:19",
"12:45",
"13:25"
],
"nick": "Wonski",
"name_and_surname": "Mathew Oxford"
}
]
you can use GraphQLList along with GraphQLString for time type like this,
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: new GraphQLList(GraphQLString)
}
})
});

Iterate through JSON Object to get all objects with property

I am trying to iterate through the following JSON document in order to get the names of skating rinks:
I can get one name; however, what I am trying to do is loop through all of the entries (there are 253) and return a list of all the names.
Here is my React component:
class Patinoire extends Component {
constructor(props) {
super(props);
this.state = { patinoires: [] };
}
componentDidMount() {
var url = 'http://localhost:3000/patinoires'
fetch(url).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(data => this.setState ({ patinoires: data.patinoires }));
}
render() {
var patinoires = this.state.patinoires;
var pjs2 = Object.values(patinoires);
var pjs3 = pjs2.map(x => x["2"].nom);
return <div>{pjs3}</div>
}
}
Right now, when using {pjs3}, I get the name of 3rd skating rink of the JSON document. How can I loop through all the entries and return the name property of all the entries?
EDIT: here is a sample of the data
{
"patinoires": {
"patinoire": [
{
"nom": [
"Aire de patinage libre, De la Savane (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
},
{
"nom": [
"Aire de patinage libre, Georges-Saint-Pierre (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
}
]
}
}
You can use Array.prototype.reduce() to flatten the result data with combination of Array.prototype.map() or Array.prototype.forEach().
Here is a running example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
patinoires: {
patinoire: [
{
nom: ["Aire de patinage libre, De la Savane (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
},
{
nom: ["Aire de patinage libre, Georges-Saint-Pierre (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
}
]
}
};
}
renderData = () => {
const { patinoires } = this.state;
const markup = patinoires.patinoire.reduce((result, current) => {
current.nom.map(n => {
return result.push(<div>{n}</div>);
});
return result;
}, []);
return markup;
}
render() {
return <div>{this.renderData()}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Try this:
var pjs2 = Object.values(patinoires);
var names = pjs2.reduce((accumulator, elem) => {
if (elem.patinoire) {
elem.patinoire.forEach(part => {
if(part.nom) {
part.nom.forEach((name) => accumulator.push(name));
}
});
}
return accumulator;
}, []);

$scope issue with gridOptions, angular-ui-grid and REST call from service

I seem to be having an issue getting my ng-grid directive to populate from a returned REST api json obj.
I have verfied that a valid json obj is returned and i have retrieved a nested obj of the data I need. It seems that it is not making it into the gridOptions function. Where myData is the correct valid json.
Any help will be greatly appreciated. I am pulling my hair out at this point.
Here is my service:
grid-service.js
'use strict';
app.factory('GridService', ['$http', '$q', function($http, $q) {
var apiUrl = "http://xx.xx.xx.xx/coName/public/index.php/";
// configure the send request
function sendRequest(config){
var deferred = $q.defer();
config.then(function(response){
deferred.resolve(response);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
}
// retrieve all
function getRoles() {
var request = $http({
method: 'GET',
url: apiUrl + 'roles'
});
return sendRequest(request);
}
return {
getRoles: getRoles
};
}]);
I inject it into my ctrl here, and my init function and gridOption functions:
app.controller('ModuleCtrl', [ '$scope', '$http', '$modal', '$filter', 'GridService', function($scope, $http, $modal, $filter, gridService) {
var initializeGrid = function(){
getRoles();
};
var getRoles = function(){
gridService.getRoles().then(function(myRoles){
var myRolesData = myRoles.data._embedded.roles;
$scope.myData = myRoles.data._embedded.roles;
console.log($scope.myData);
});
};
$scope.gridOptions = {
data: 'myData',
enableRowSelection: true,
enableCellEditOnFocus: true,
showSelectionCheckbox: true,
selectedItems: $scope.selectedRows,
columnDefs: [{
field: 'ID',
displayName: 'Id',
enableCellEdit: false
}, {
field: 'APP_ID',
displayName: 'Module ID',
enableCellEdit: false
}, {
field: 'RLDESC',
displayName: 'Role Description',
enableCellEdit: true
}, {
field: 'APDESC',
displayName: 'Module Description',
enableCellEdit: true
}, {
field: 'ZEND_DB_ROWNUM',
displayName: 'Record number',
enableCellEdit: false
}]
};
// fire it up
initializeGrid();
}
My complete json:
{
"_links": {
"self": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
},
"describedBy": {
"href": "Some Fun Stuff"
},
"first": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles"
},
"last": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
}
},
"_embedded": {
"roles": [
{
"ID": 1,
"APP_ID": 1,
"RLDESC": "Admin",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "1"
},
{
"ID": 2,
"APP_ID": 1,
"RLDESC": "User",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "2"
},
{
"ID": 4,
"APP_ID": 1,
"RLDESC": "SuperUser",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "3"
}
]
},
"page_count": 1,
"page_size": 25,
"total_items": 3
}
Remove the following line from the gridOptions
data: 'myData'
Then in getRoles() use
$scope.gridOptions.data = myRolesData;
instead of
$scope.myData = myRoles.data._embedded.roles;
(Maybe you need $scope.myData for some other reason than the grid, but if not I think the above is all you need. I have not tested this live, but it should work.)