Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include zero count active facets in facet options #79

Merged
merged 4 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
"homepage": "https://github.com/mitodl/course-search-utils#readme",
"dependencies": {
"@mitodl/open-api-axios": "^2024.3.22",
"@testing-library/react": "12",
"@testing-library/user-event": "^14.5.2",
"axios": "^1.6.7",
"fuse.js": "^7.0.0",
"query-string": "^6.13.1",
Expand Down
228 changes: 155 additions & 73 deletions src/facet_display/FacetDisplay.test.tsx
Original file line number Diff line number Diff line change
@@ -1,118 +1,200 @@
import React from "react"
import { shallow } from "enzyme"
import { render, screen, within } from "@testing-library/react"
import user from "@testing-library/user-event"
Comment on lines -2 to +3
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The vast majority of the line changes in this PR are from removing enzyme in this test file, and adding @testing-library/react, @testing-library/user-event.

I was going to add more tests in this file, and I did not want to add enzyme tests since they are fragile / don't work with React 17, 18. (In previous PR, I had to alter the test file because I extracted AvailableFacets from FacetDisplay https://github.com/mitodl/course-search-utils/pull/78/files#diff-0b2ec90271aa9923bd1a4e5747946849aa084238d325cc529cda4848f503b8a3). So I rewrote the enzyme tests with @testing-library.

I also added some tests... E.g., I didn't see tests for clicking the expand/collapse buttons.


import {
default as FacetDisplay,
AvailableFacets,
getDepartmentName,
getLevelName
} from "./FacetDisplay"
import { FacetManifest, Facets } from "./types"
import FacetDisplay, { getDepartmentName } from "./FacetDisplay"
import type { FacetDisplayProps } from "./FacetDisplay"
import { Bucket, FacetManifest, Facets } from "./types"

describe("FacetDisplay component", () => {
const facetMap: FacetManifest = [
const defaultFacetMap: FacetManifest = [
{
name: "topic",
title: "Topics",
useFilterableFacet: false,
expandedOnLoad: false
},
{
name: "resource_type",
title: "Types",
useFilterableFacet: false,
expandedOnLoad: false
expandedOnLoad: true
},
{
name: "department",
title: "Departments",
useFilterableFacet: false,
expandedOnLoad: true,
labelFunction: getDepartmentName
},
{
name: "level",
title: "Level",
useFilterableFacet: false,
expandedOnLoad: true,
labelFunction: getLevelName
expandedOnLoad: true
}
]

function setup() {
const defaultAggregations = {
topic: [
{ key: "Cats", doc_count: 10 },
{ key: "Dogs", doc_count: 20 },
{ key: "Monkeys", doc_count: 30 }
],
department: [
{ key: "1", doc_count: 100 },
{ key: "2", doc_count: 200 }
]
}

const setup = ({
props,
aggregations = defaultAggregations
}: {
props?: Partial<FacetDisplayProps>
aggregations?: Record<string, Bucket[]>
} = {}) => {
const activeFacets = {}
const facetOptions = jest.fn()
const facetOptions = (group: string) => aggregations[group] ?? []
const clearAllFilters = jest.fn()
const onFacetChange = jest.fn()

const render = (props = {}) =>
shallow(
const view = render(
<FacetDisplay
facetMap={defaultFacetMap}
facetOptions={facetOptions}
activeFacets={activeFacets}
clearAllFilters={clearAllFilters}
onFacetChange={onFacetChange}
{...props}
/>
)
const spies = {
onFacetChange,
clearAllFilters
}
const rerender = (newProps: Partial<FacetDisplayProps>) => {
view.rerender(
<FacetDisplay
facetMap={facetMap}
facetMap={defaultFacetMap}
facetOptions={facetOptions}
activeFacets={activeFacets}
clearAllFilters={clearAllFilters}
onFacetChange={onFacetChange}
{...props}
{...newProps}
/>
)
return { render, clearAllFilters }
}
return { view, spies, rerender }
}

test("renders a FacetDisplay with expected FilterableFacets", async () => {
const { render } = setup()
const wrapper = render()
const facets = wrapper.find(AvailableFacets).dive().children()
expect(facets).toHaveLength(4)
facets.map((facet, key) => {
expect(facet.prop("name")).toBe(facetMap[key].name)
expect(facet.prop("title")).toBe(facetMap[key].title)
expect(facet.prop("expandedOnLoad")).toBe(facetMap[key].expandedOnLoad)
test("Renders facets with expected titles", async () => {
setup()
screen.getByRole("button", { name: defaultFacetMap[0].title })
screen.getByRole("button", { name: defaultFacetMap[1].title })
})

test.each([{ expandedOnLoad: false }, { expandedOnLoad: true }])(
"Initially expanded based on expandedOnLoad ($expandedOnLoad)",
({ expandedOnLoad }) => {
const facetMap = [{ ...defaultFacetMap[0], expandedOnLoad }]
setup({
props: { facetMap }
})
screen.getByRole("button", {
name: facetMap[0].title,
expanded: expandedOnLoad
})
const checkboxes = screen.queryAllByRole("checkbox")
expect(checkboxes).toHaveLength(expandedOnLoad ? 3 : 0)
}
)

test("Clicking facet title toggles expanded state", async () => {
setup({
props: { facetMap: [defaultFacetMap[0]] }
})
const button = screen.getByRole("button", {
name: defaultFacetMap[0].title
})
const checkboxCount = () => screen.queryAllByRole("checkbox").length
await user.click(button)
expect(button.getAttribute("aria-expanded")).toBe("false")
expect(checkboxCount()).toBe(0)
await user.click(button)
expect(button.getAttribute("aria-expanded")).toBe("true")
expect(checkboxCount()).toBe(3)
})

test("shows filters which are active", () => {
test("Shows filters which are active", async () => {
const activeFacets: Facets = {
topic: ["Academic Writing", "Accounting", "Aerodynamics"],
resource_type: [],
department: ["1", "2"]
topic: ["Cats", "Dogs"],
department: ["1"]
}
const { spies } = setup({ props: { activeFacets } })
const activeDisplay = document.querySelector(".active-search-filters")
if (!(activeDisplay instanceof HTMLElement)) {
throw new Error("Expected activeDisplay to exist")
}
within(activeDisplay).getByText("Cats")
within(activeDisplay).getByText("Dogs")
within(activeDisplay).getByText("1")

const { render, clearAllFilters } = setup()
const wrapper = render({
activeFacets
await user.click(screen.getByRole("button", { name: "Clear All" }))
expect(spies.clearAllFilters).toHaveBeenCalled()
await user.click(screen.getAllByRole("button", { name: "clear filter" })[0])
expect(spies.onFacetChange).toHaveBeenCalledWith("topic", "Cats", false)
})

test("Clicking a facet checkbox calls onFacetChange", async () => {
const { spies } = setup({
props: {
facetMap: [
{
...defaultFacetMap[0],
expandedOnLoad: true
}
]
}
})
expect(
wrapper
.find(".active-search-filters")
.find("SearchFilter")
.map(el => el.prop("value"))
).toEqual(["Academic Writing", "Accounting", "Aerodynamics", "1", "2"])
wrapper.find(".clear-all-filters-button").simulate("click")
expect(clearAllFilters).toHaveBeenCalled()
await user.click(screen.getByRole("checkbox", { name: "Cats" }))
expect(spies.onFacetChange).toHaveBeenCalledWith("topic", "Cats", true)
})

test("it accepts a label function to convert codes to names", () => {
setup({
props: {
facetMap: [
{
...defaultFacetMap[1],
labelFunction: getDepartmentName,
expandedOnLoad: true
}
]
}
})
screen.getByRole("checkbox", {
name: "Civil and Environmental Engineering"
})
screen.getByRole("checkbox", {
name: "Mechanical Engineering"
})
})

test("Automically includes a zero-count option for active facets with no matches", () => {
const activeFacets: Facets = {
topic: [],
resource_type: [],
department: ["1"],
level: ["graduate"]
topic: ["Cats"]
}

const { render, clearAllFilters } = setup()
const wrapper = render({
activeFacets
const { rerender } = setup({
props: {
activeFacets,
facetMap: [
{
...defaultFacetMap[0],
expandedOnLoad: true
}
]
}
})
const checkboxCount = () => screen.getAllByRole("checkbox").length
expect(checkboxCount()).toBe(3)
screen.getByRole("checkbox", { name: "Cats" })
screen.getByRole("checkbox", { name: "Dogs" })
screen.getByRole("checkbox", { name: "Monkeys" })
rerender({
activeFacets: {
topic: ["Cats", "Dragons"]
}
})
expect(
wrapper
.find(".active-search-filters")
.find("SearchFilter")
.map(el =>
el.render().find(".active-search-filter-label").first().html()
)
).toEqual(["Civil and Environmental Engineering", "Graduate"])
wrapper.find(".clear-all-filters-button").simulate("click")
expect(clearAllFilters).toHaveBeenCalled()
expect(checkboxCount()).toBe(4)
screen.getByRole("checkbox", { name: "Dragons" })
})
})
43 changes: 40 additions & 3 deletions src/facet_display/FacetDisplay.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react"
import React, { useCallback } from "react"
import FilterableFacet from "./FilterableFacet"
import Facet from "./Facet"
import SearchFilter from "./SearchFilter"
Expand All @@ -9,6 +9,12 @@ export type BucketWithLabel = Bucket & { label: string }

interface FacetDisplayProps {
facetMap: FacetManifest
/**
* Returns the aggregation options for a given group.
*
* If `activeFacets` includes a facet with no results, that facet will
* automatically be included in the facet options.
*/
facetOptions: (group: string) => Aggregation | null
activeFacets: Facets
clearAllFilters: () => void
Expand Down Expand Up @@ -47,20 +53,50 @@ const resultsWithLabels = (
return newResults
}

/**
* Augment the facet buckets for `groupKey` with active values that have no
* results.
*/
const includeActiveZerosInBuckets = (
groupKey: string,
buckets: Bucket[],
params: Facets
) => {
const opts = [...buckets]
const active = params[groupKey as keyof Facets] ?? []
const actives = Array.isArray(active) ? active : [active]
actives.forEach(key => {
if (!opts.find(o => o.key === key)) {
opts.push({ key: String(key), doc_count: 0 })
}
})
return opts
}

const AvailableFacets: React.FC<Omit<FacetDisplayProps, "clearAllFilters">> = ({
facetMap,
facetOptions,
activeFacets,
onFacetChange
}) => {
const allFacetOptions: FacetDisplayProps["facetOptions"] = useCallback(
name => {
return includeActiveZerosInBuckets(
name,
facetOptions(name) ?? [],
activeFacets
)
},
[facetOptions, activeFacets]
)
return (
<>
{facetMap.map(facetSetting =>
facetSetting.useFilterableFacet ? (
<FilterableFacet
key={facetSetting.name}
results={resultsWithLabels(
facetOptions(facetSetting.name) || [],
allFacetOptions(facetSetting.name) || [],
facetSetting.labelFunction
)}
name={facetSetting.name}
Expand All @@ -77,7 +113,7 @@ const AvailableFacets: React.FC<Omit<FacetDisplayProps, "clearAllFilters">> = ({
title={facetSetting.title}
name={facetSetting.name}
results={resultsWithLabels(
facetOptions(facetSetting.name) || [],
allFacetOptions(facetSetting.name) || [],
facetSetting.labelFunction
)}
onUpdate={e =>
Expand Down Expand Up @@ -149,3 +185,4 @@ const FacetDisplay = React.memo(

export default FacetDisplay
export { AvailableFacets }
export type { FacetDisplayProps }
Loading
Loading