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

[BIOMAGE-2001] Replace gene selection #759

Merged
merged 26 commits into from
Jul 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
52203c5
WIP - replace gene selection, add autoscroll
jszpila314 Jul 5, 2022
781d964
remove and adjust tests
jszpila314 Jul 6, 2022
3cc8488
adjust tests and comments
jszpila314 Jul 6, 2022
5d074dd
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 6, 2022
7bb9824
Remove test from MarkerGeneSelection
jszpila314 Jul 6, 2022
bf58496
add functions dependent on plot
jszpila314 Jul 13, 2022
c942c35
merge master, resolve merge conflict by changing imports in marker-he…
jszpila314 Jul 13, 2022
ca35596
update dot-plot snapshot
jszpila314 Jul 15, 2022
d183f18
Merge branch 'master' into replace-gene-selection
aerlaut Jul 15, 2022
5d1b143
resolve comments
jszpila314 Jul 16, 2022
605f0e5
add search and re-order tests to dot plot
jszpila314 Jul 20, 2022
ae57b16
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 20, 2022
f2a1b36
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 20, 2022
6aa28d6
Merge branch 'replace-gene-selection' of https://github.com/hms-dbmi-…
jszpila314 Jul 20, 2022
f7f9fce
fix reset button in dot plot
jszpila314 Jul 20, 2022
f64769f
add comments for config change cases
jszpila314 Jul 20, 2022
9d644ad
fix scroll bugs, add scroll instructions
jszpila314 Jul 21, 2022
5c374fa
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 21, 2022
599b2dc
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 21, 2022
7d9edc0
fix dot plot reset and switching to marker genes
jszpila314 Jul 22, 2022
5ebe010
Merge branch 'master' into replace-gene-selection
jszpila314 Jul 22, 2022
b0d8c5d
fix ant tree colours
jszpila314 Jul 22, 2022
85e2da8
hide the plot when all genes are removed
jszpila314 Jul 22, 2022
848553e
correct comment
jszpila314 Jul 22, 2022
3e9167d
update previous config when deleting last gene
jszpila314 Jul 22, 2022
42a5ac9
fix plot name in gene selection instructions
jszpila314 Jul 22, 2022
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
35 changes: 5 additions & 30 deletions src/__test__/components/plots/styling/MarkerGeneSelection.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,49 +12,24 @@ import { plotTypes } from 'utils/constants';

const mockOnUpdate = jest.fn();
const mockOnReset = jest.fn();
const mockOnGeneEnter = jest.fn();

const plotType = plotTypes.DOT_PLOT;

const defaultProps = {
onUpdate: mockOnUpdate,
onReset: mockOnReset,
onGeneEnter: mockOnGeneEnter,
plotUuid: 'dotPlotMain',
experimentId: 'experimentId',
searchBarUuid: 'searchBarUuid',
};

const plotType = plotTypes.DOT_PLOT;

const markerGeneSelectionFactory = createTestComponentFactory(MarkerGeneSelection, defaultProps);

describe('MarkerGeneSelection', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('Should show the custom gene input by default', async () => {
const mockConfig = initialPlotConfigStates[plotType];

await act(async () => {
render(
markerGeneSelectionFactory({ config: mockConfig }),
);
});

// Expect screen to show the custom gene selection input by default
expect(screen.getByText(/Type in a gene name/i)).toBeInTheDocument();

// Typing genes and then pressing enter
const geneInput = screen.getByRole('combobox');

// This is not wrapped in act() because changes to the value causes a re-render
// which causes mockOnGeneEnter to lose its memory of having been called
userEvent.type(geneInput, 'ABC{enter}');

// Expect geneEnter to be called
expect(mockOnGeneEnter).toHaveBeenCalledTimes(1);
const inputValue = mockOnGeneEnter.mock.calls[0][0];

expect(inputValue).toEqual(['ABC']);
});

it('Should show the number of marker genes input', async () => {
const mockConfig = { ...initialPlotConfigStates[plotType], useMarkerGenes: true };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,6 @@ Array [
},
Object {},
],
Array [
Object {
"data": Array [],
"filename": "Test_Experiment-dot_plot-louvain-All",
},
Object {},
],
Array [
Object {
"data": Array [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import _ from 'lodash';

import { act } from 'react-dom/test-utils';
import { render, screen, fireEvent } from '@testing-library/react';
import { mount } from 'enzyme';
import { within } from '@testing-library/dom';
import '@testing-library/jest-dom';
import { Provider } from 'react-redux';

Expand Down Expand Up @@ -33,6 +35,9 @@ import userEvent from '@testing-library/user-event';
import { plotNames } from 'utils/constants';
import ExportAsCSV from 'components/plots/ExportAsCSV';

import waitForComponentToPaint from '__test__/test-utils/waitForComponentToPaint';
import { arrayMoveImmutable } from 'utils/array-move';

jest.mock('components/plots/ExportAsCSV', () => jest.fn(() => (<></>)));
jest.mock('components/header/UserButton', () => () => <></>);
jest.mock('react-resize-detector', () => (props) => {
Expand Down Expand Up @@ -86,6 +91,23 @@ const mockAPIResponse = _.merge(
const defaultProps = { experimentId };
const dotPlotPageFactory = createTestComponentFactory(DotPlotPage, defaultProps);

// Helper function to get genes held within the tree
const getTreeGenes = (container) => {
const treeNodeList = container.querySelectorAll('span[class*=ant-tree-title]');
return Array.from(treeNodeList).map((node) => node.textContent);
};

// Helper function to get current order of displayed genes in enzyme tests
const getCurrentGeneOrder = (component) => {
const treeNodes = component.find('div.ant-tree-treenode');
const newOrder = [];
treeNodes.forEach((node) => {
newOrder.push(node.text());
});
newOrder.splice(0, 1);
return newOrder;
};

const renderDotPlot = async (store) => {
await act(async () => {
render(
Expand All @@ -96,6 +118,14 @@ const renderDotPlot = async (store) => {
});
};

const renderDotPlotForEnzyme = async (store) => (
mount(
<Provider store={store}>
{dotPlotPageFactory()}
</Provider>,
)
);

enableFetchMocks();

let storeState = null;
Expand Down Expand Up @@ -226,7 +256,7 @@ describe('Dot plot page', () => {
// 2nd call to load dot plot
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]())
// 3nd call to load dot plot
// 3rd call to load dot plot
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]());

Expand Down Expand Up @@ -271,4 +301,249 @@ describe('Dot plot page', () => {
expect(screen.getByText(/A comparison can not be run to determine the top marker genes/i)).toBeInTheDocument();
expect(screen.getByText(/Select another option from the 'Select data' menu/i)).toBeInTheDocument();
});

it('removing a gene keeps the order', async () => {
await renderDotPlot(storeState);

const geneTree = screen.getByRole('tree');

// first three genes of the data should be loaded by default
const loadedGenes = paginatedGeneExpressionData.rows.map((row) => (row.gene_names)).slice(0, 3);

// The genes in Data 5 should be in the tree
loadedGenes.forEach((geneName) => {
expect(within(geneTree).getByText(geneName)).toBeInTheDocument();
});

// Remove a gene using the X button
const genesListBeforeRemoval = getTreeGenes(geneTree);

const geneToRemove = within(geneTree).getByText(genesListBeforeRemoval[1]);

const geneRemoveButton = geneToRemove.nextSibling.firstChild;

userEvent.click(geneRemoveButton);

const genesListAfterRemoval = getTreeGenes(geneTree);

// remove element from list manually to compare
genesListBeforeRemoval.splice(1, 1);

// The gene should be deleted from the list
expect(_.isEqual(genesListAfterRemoval, genesListBeforeRemoval)).toEqual(true);
});

it('searches for genes and adds a valid gene', async () => {
await renderDotPlot(storeState);

const geneTree = screen.getByRole('tree');
const initialOrder = getTreeGenes(geneTree);

// check placeholder text is loaded
expect(screen.getByText('Search for genes...')).toBeInTheDocument();

const searchBox = screen.getByRole('combobox');

// search for genes using lowercase
userEvent.type(searchBox, 'ap');

// antd creates multiple elements for options
// find option element by title, clicking on element with role='option' does nothing
const option = screen.getByTitle('Apoe');

await act(async () => {
// the element has pointer-events set to 'none', skip check
// based on https://stackoverflow.com/questions/61080116
userEvent.click(option, undefined, { skipPointerEventsCheck: true });
});

// check the search text is cleared after selecting a valid option
expect(searchBox.value).toBe('');

// check the selected gene was added
expect(within(geneTree).getByText('Apoe')).toBeInTheDocument();

// check the genes were not re-ordered when adding
initialOrder.push('Apoe');
expect(_.isEqual(initialOrder, getTreeGenes(geneTree))).toEqual(true);
});

it('adds an already loaded gene and clears the input', async () => {
await renderDotPlot(storeState);

const searchBox = screen.getByRole('combobox');

userEvent.type(searchBox, 'ly');

const option = screen.getByTitle('Lyz2');

// expecting option to be disabled throws error, click the option instead and check reaction
await act(async () => {
userEvent.click(option, undefined, { skipPointerEventsCheck: true });
});

// search box shouldn't clear when selecting an already loaded gene
expect(searchBox.value).toBe('ly');

// clear button is automatically generated by antd and cannot be easily accessed
const clearButton = searchBox.closest('div[class*=ant-select-auto-complete]').lastChild;

userEvent.click(clearButton);

expect(searchBox.value).toBe('');
});

it('resets the data', async () => {
await renderDotPlot(storeState);

seekFromS3
.mockReset()
// 1st call to list genes
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]())
// 2nd call to load dot plot
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]())
// 3rd call to load dot plot
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]());

// add a gene to prepare for reset
const searchBox = screen.getByRole('combobox');

userEvent.type(searchBox, 'ap');

const option = screen.getByTitle('Apoe');

await act(async () => {
userEvent.click(option, undefined, { skipPointerEventsCheck: true });
});

const resetButton = screen.getAllByText('Reset')[1];

await act(async () => {
userEvent.click(resetButton);
});

// expect the gene only within the options of the search box, antd creates 2 elements
expect(screen.getAllByText('Apoe').length).toBe(2);
});
});

// drag and drop is impossible in RTL, use enzyme
describe('Drag and drop enzyme tests', () => {
let component;
let tree;
let loadedGenes;

beforeEach(async () => {
jest.clearAllMocks();

seekFromS3
.mockReset()
// 1st call to list genes
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]())
// 2nd call to paginated gene expression
.mockImplementationOnce(() => null)
.mockImplementationOnce((Etag) => mockWorkerResponses[Etag]());

fetchMock.resetMocks();
fetchMock.mockIf(/.*/, mockAPI(mockAPIResponse));

storeState = makeStore();

await storeState.dispatch(loadBackendStatus(experimentId));

storeState.dispatch({
type: EXPERIMENT_SETTINGS_INFO_UPDATE,
payload: {
experimentId: fake.EXPERIMENT_ID,
experimentName: fake.EXPERIMENT_NAME,
},
});

component = await renderDotPlotForEnzyme(storeState);

await waitForComponentToPaint(component);

component.update();

// antd renders 5 elements, use the first one
tree = component.find({ 'data-testid': 'HierachicalTreeGenes' }).at(0);
loadedGenes = paginatedGeneExpressionData.rows.map((row) => (row.gene_names)).slice(0, 3).reverse();
});

it('changes nothing on drop in place', async () => {
// default genes are in the tree
loadedGenes.forEach((geneName) => {
expect(tree.containsMatchingElement(geneName));
});

// dropping in place does nothing
const info = {
dragNode: { key: 1, pos: '0-1' },
dropPosition: 1,
dropToGap: true,
};

tree.getElement().props.onDrop(info);

await act(async () => {
component.update();
});

const newOrder = getCurrentGeneOrder(component);

expect(_.isEqual(newOrder, loadedGenes)).toEqual(true);
});

it('changes nothing when not dropped in gap', async () => {
// default genes are in the tree
loadedGenes.forEach((geneName) => {
expect(tree.containsMatchingElement(geneName));
});

// not dropping to gap does nothing
const info = {
dragNode: { key: 0, pos: '0-0' },
dropPosition: 2,
dropToGap: false,
};

tree.getElement().props.onDrop(info);

await act(async () => {
component.update();
});

const newOrder = getCurrentGeneOrder(component);

expect(_.isEqual(newOrder, loadedGenes)).toEqual(true);
});

it('re-orders genes correctly', async () => {
// default genes are in the tree
loadedGenes.forEach((geneName) => {
expect(tree.containsMatchingElement(geneName));
});
// dropping to gap re-orders genes
const info = {
dragNode: { key: 0, pos: '0-0' },
dropPosition: 2,
dropToGap: true,
};

tree.getElement().props.onDrop(info);

await act(async () => {
component.update();
});

const newOrder = getCurrentGeneOrder(component);

const expectedOrder = arrayMoveImmutable(loadedGenes, 0, 1);

expect(_.isEqual(newOrder, expectedOrder)).toEqual(true);
});
});
Loading