Skip to content

Commit

Permalink
Merge pull request #13 from saleem-hadad/feature/add-value-metric-uni…
Browse files Browse the repository at this point in the history
…t-tests

Add value metric unit tests #features
  • Loading branch information
saleem-hadad authored Apr 23, 2022
2 parents 10fddf4 + 3765904 commit 824c901
Show file tree
Hide file tree
Showing 23 changed files with 230 additions and 142 deletions.
5 changes: 5 additions & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { server } from './resources/js/mocks/server.js'

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@tailwindcss/forms": "^0.4.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^14.1.1",
"autoprefixer": "^10.2.4",
"axios": "^0.21",
"babel-jest": "^27.5.1",
Expand All @@ -45,5 +46,10 @@
"numbro": "^2.3.6",
"react-chartjs-2": "^4.0.0",
"urql": "^2.2.0"
},
"jest": {
"setupFilesAfterEnv": [
"./jest.setup.js"
]
}
}
2 changes: 1 addition & 1 deletion public/css/app.css

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion public/js/app.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions public/mix-manifest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"/js/app.js": "/js/app.js?id=646cbe42f9883c5bee75",
"/css/app.css": "/css/app.css?id=302229d53296b2231e13"
"/js/app.js": "/js/app.js?id=9f1561cb00efdc560d9b",
"/css/app.css": "/css/app.css?id=bd9462ef1c7aca6afb62"
}
31 changes: 6 additions & 25 deletions resources/js/Api/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ export const deleteResource = ({id, resource}) => {
.toPromise();
}

export const query = (query, range = null) => {
export const query = (query, range = null, queryName = null) => {
const queryCustomName = queryName ? queryName : query;

if(range == null) {
return client
.query(gql`
query {
query ${queryCustomName} {
${query}
}
`)
Expand All @@ -26,30 +28,9 @@ export const query = (query, range = null) => {

return client
.query(gql`
query {
query ${queryCustomName} {
${query}(range: """${range}""")
}
`)
`, {range})
.toPromise();
}





















11 changes: 6 additions & 5 deletions resources/js/Components/Domain/PartitionMetric.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { sumBy } from 'lodash';
import { query } from '../../Api';
import Card from "../Global/Card";
import LoadingView from "../Global/LoadingView";
import { colors, formatNumber, getTailwindColor } from '../../Utils';

Chart.register(ArcElement, DoughnutController);

Expand All @@ -18,7 +19,7 @@ export default function PartitionMetric({ name, graphql_query, ranges, relation
useEffect(() => {
if(! relation) { return; }

query(relation.graphql_query + `{ id ${relation.display_using} }`)
query(relation.graphql_query + `{ id ${relation.display_using} }`, null, 'CustomQuery')
.then(({data}) => {
setRelationData(data[relation.graphql_query])
setSelectedRelationId(data[relation.graphql_query][0].id)
Expand All @@ -31,7 +32,7 @@ export default function PartitionMetric({ name, graphql_query, ranges, relation

if(relation) {
if (selectedRelationId) {
query(graphql_query + `(range: """${selectedRange}""" ${relation.foreign_key}: ${selectedRelationId})`)
query(graphql_query + `(range: """${selectedRange}""" ${relation.foreign_key}: ${selectedRelationId})`, null, 'CustomQuery')
.then(({data}) => setData(JSON.parse(data[graphql_query])))
.catch(console.error)
}
Expand All @@ -58,7 +59,7 @@ export default function PartitionMetric({ name, graphql_query, ranges, relation
labels: data.map(item => item.label),
datasets: [{
data: data.map(item => item.value),
backgroundColor: Engine.colors().map(color => color.hex),
backgroundColor: colors().map(color => color.hex),
cutout: '75%',
borderWidth: 0
}]
Expand Down Expand Up @@ -117,8 +118,8 @@ export default function PartitionMetric({ name, graphql_query, ranges, relation
<div className="overflow-hidden overflow-y-auto max-h-22">
<ul className="list-reset">
{data.map((item, index) => <li key={index} className="text-xs text-gray-700 leading-normal">
<span className={`inline-block rounded-full w-2 h-2 mr-2 ${Engine.getTailwindColor(index)}`} />
{item.label} ({AppCurrency} {item.value} - {total > 0 && Engine.formatNumber(item.value * 100 / total) + "%"})
<span className={`inline-block rounded-full w-2 h-2 mr-2 ${getTailwindColor(index)}`} />
{item.label} ({AppCurrency} {item.value} - {total > 0 && formatNumber(item.value * 100 / total) + "%"})
</li>)}
</ul>
</div>
Expand Down
4 changes: 2 additions & 2 deletions resources/js/Components/Domain/TrendMetric.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function TrendMetric({ name, graphql_query, ranges, relation }) {
useEffect(() => {
if(! relation) { return; }

query(relation.graphql_query + `{ id ${relation.display_using} }`)
query(relation.graphql_query + `{ id ${relation.display_using} }`, null, 'CustomQuery')
.then(({data}) => {
setRelationData(data[relation.graphql_query])
setSelectedRelationId(data[relation.graphql_query][0].id)
Expand All @@ -30,7 +30,7 @@ export default function TrendMetric({ name, graphql_query, ranges, relation }) {

if(relation) {
if (selectedRelationId) {
query(graphql_query + `(range: """${selectedRange}""" ${relation.foreign_key}: ${selectedRelationId})`)
query(graphql_query + `(range: """${selectedRange}""" ${relation.foreign_key}: ${selectedRelationId})`, null, 'CustomQuery')
.then(({data}) => setData(JSON.parse(data[graphql_query])))
.catch(console.error)
}
Expand Down
16 changes: 7 additions & 9 deletions resources/js/Components/Domain/ValueMetric.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ import React, { useEffect, useState } from 'react';
import { query } from '../../Api';
import Card from "../Global/Card";
import LoadingView from "../Global/LoadingView";
import { formatNumber, getAppCurrency } from '../../Utils';

function ValueMetric({name, graphql_query, ranges}) {
export default function ValueMetric({name, graphql_query, ranges}) {
const [data, setData] = useState(null);
const [selectedRange, setSelectedRange] = useState(ranges ? ranges[0].key : null);

useEffect(() => {
useEffect(async () => {
setData(null);

query(graphql_query, selectedRange)
.then(({data}) => setData(data[graphql_query]))
.catch(console.error)
let { data } = await query(graphql_query, selectedRange);
setData(data[graphql_query])
}, [selectedRange])

if(data == null) {
Expand All @@ -39,11 +39,9 @@ function ValueMetric({name, graphql_query, ranges}) {
</div>

<p className="flex items-center text-4xl mb-4">
{ AppCurrency } { Engine.formatNumber(data) }
{ getAppCurrency() } { formatNumber(data) }
</p>
</div>
</Card>
);
}

export default ValueMetric;
};
20 changes: 1 addition & 19 deletions resources/js/Components/Domain/__tests__/Delete.test.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
import * as React from 'react'
import { cleanup, screen, render, fireEvent, waitFor } from '@testing-library/react';
import { screen, render, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import 'intersection-observer';
import { graphql } from 'msw'
import {setupServer} from 'msw/node'

import Delete from '../Delete';

const server = setupServer(
graphql.mutation('DeleteResource', (req, res, ctx) => {
return res(
ctx.data({id: 1}),
)
})
)

beforeAll(() => server.listen())
afterEach(() => {
server.resetHandlers()
cleanup()
})
afterAll(() => server.close())

it('If item not passed then delete popup will not be shown', () => {
render(<Delete />);

Expand Down
71 changes: 71 additions & 0 deletions resources/js/Components/Domain/__tests__/ValueMetric.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import * as React from 'react'
import { screen, render, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';

import ValueMetric from '../ValueMetric';

it('it fetches data once loaded and stop loader once data is fetched', async () => {
render(<ValueMetric name="Some Metric" graphql_query="valueMetricSampleQuery" />);

expect(screen.getByTestId('loading-view')).toBeVisible()

await waitForElementToBeRemoved(() => screen.queryByTestId('loading-view'))
await waitFor(() => expect(screen.getByText(/some metric/i)).toBeVisible())
});


it('ranges provided and select first by default', async () => {
const ranges = [
{name: "Current Month", key: "current-month", start: "2022-04-01", end: "2022-04-30"},
{name: "Last Month", key: "last-month", start: "2022-03-01", end: "2022-03-31"}
];

render(<ValueMetric name="Some Metric" graphql_query="valueMetricSampleQuery" ranges={ranges} />);

await waitFor(() => {
expect(screen.getByRole('option', {name: 'Current Month'}).selected).toBe(true)
expect(screen.getByRole('option', {name: 'Last Month'}).selected).toBe(false)
})
});

it('it allows to select a range if ranges provides', async () => {
const ranges = [
{name: "Current Month", key: "current-month", start: "2022-04-01", end: "2022-04-30"},
{name: "Last Month", key: "last-month", start: "2022-03-01", end: "2022-03-31"}
];

render(<ValueMetric name="Some Metric" graphql_query="valueMetricSampleQuery" ranges={ranges} />);

await waitFor(async () => {
await userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', {name: 'Last Month'}),
)
})

await waitFor(() => {
expect(screen.getByRole('option', {name: 'Current Month'}).selected).toBe(false)
expect(screen.getByRole('option', {name: 'Last Month'}).selected).toBe(true)
})
});

it('it fetches data if a range is selected', async () => {
const ranges = [
{name: "Current Month", key: "current-month", start: "2022-04-01", end: "2022-04-30"},
{name: "Last Month", key: "last-month", start: "2022-03-01", end: "2022-03-31"}
];

render(<ValueMetric name="Some Metric" graphql_query="valueMetricSampleQuery" ranges={ranges} />);

await waitFor(() => expect(screen.getByText(/3k/i)).toBeVisible())

await waitFor(async () => {
await userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', {name: 'Last Month'}),
)
})

await waitFor(() => expect(screen.getByText(/2k/i)).toBeVisible())
})
2 changes: 1 addition & 1 deletion resources/js/Components/Global/LoadingView.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Loader from './Loader';

function LoadingView() {
return (
<div className="rounded-lg flex items-center justify-center absolute left-0 right-0 top-0 bottom-0 z-50">
<div data-testid="loading-view" className="rounded-lg flex items-center justify-center absolute left-0 right-0 top-0 bottom-0 z-50">
<Loader />
</div>
);
Expand Down
60 changes: 0 additions & 60 deletions resources/js/Engine.js

This file was deleted.

Loading

0 comments on commit 824c901

Please sign in to comment.