Testing a plugin
Fast unit tests (adapters, models) and jsdom render tests (components) cover most plugin logic; browser tests drive the built app. The tools depend on where the plugin is developed:
- A plugin started from a
plugin template runs vitest.
pnpm testruns the jsdom tests undertest/, such asHelloView.test.tsx, which renders the example view with@testing-library/react.pnpm test:e2ebuilds the bundle and loads it in Puppeteer against a nightly JBrowse, whichjbrowse createdownloads on the first run. The adapter tests below apply with vitest in place of Jest; render a component directly, asHelloView.test.tsxdoes. - A plugin developed in the jbrowse-components repository runs Jest. The
session and component examples use
@jbrowse/web/testUtils, which is part of that repository's private@jbrowse/webpackage and is not published to npm. Thebrowser-tests/harness,pnpm test <directory>andpnpm test:browserexist only in that repository.
Adapter tests
Construct the adapter from its config schema and read features. Gff3Adapter's
own test, in full:
import { firstValueFrom } from 'rxjs'
import { toArray } from 'rxjs/operators'
import Gff3Adapter from './Gff3Adapter.ts'
import configSchema from './configSchema.ts'
describe('adapter can fetch features from volvox.gff3', () => {
let adapter: Gff3Adapter
beforeEach(() => {
adapter = new Gff3Adapter(
configSchema.create({
gffLocation: {
localPath: require.resolve('../test_data/volvox.sort.gff3'),
},
}),
)
})
it('test getfeatures on gff plain text adapter', async () => {
const features = adapter.getFeatures({
refName: 'ctgB',
start: 0,
end: 200000,
})
expect(await adapter.hasDataForRefName('ctgA')).toBe(true)
expect(await adapter.hasDataForRefName('ctgB')).toBe(true)
const featuresArray = await firstValueFrom(features.pipe(toArray()))
// There are only 4 features in ctgB
expect(featuresArray.length).toBe(4)
const featuresJsonArray = featuresArray.map(f => f.toJSON())
expect(featuresJsonArray).toMatchSnapshot()
})
})
describe('discontinuous feature parsing', () => {
it('keeps every segment of a CDS that shares one ID across lines', async () => {
const adapter = new Gff3Adapter(
configSchema.create({
gffLocation: {
localPath: require.resolve('../test_data/disjoint_cds.gff3'),
},
}),
)
const features = adapter.getFeatures({
refName: 'ctgA',
start: 0,
end: 1000,
})
const featuresArray = await firstValueFrom(features.pipe(toArray()))
const gene = featuresArray[0]!.toJSON()
const mrna = gene.subfeatures![0]!
const cds = mrna.subfeatures!.filter(f => f.type === 'CDS')
expect(cds.length).toBe(3)
expect(cds.map(f => f.start)).toEqual([0, 199, 399])
})
})
describe('top-level discontinuous features', () => {
it('folds a cDNA_match into one feature with a block per line', async () => {
const adapter = new Gff3Adapter(
configSchema.create({
gffLocation: {
localPath: require.resolve('../test_data/cdna_match.gff3'),
},
}),
)
const features = adapter.getFeatures({
refName: 'ctgA',
start: 0,
end: 10000,
})
const featuresArray = await firstValueFrom(features.pipe(toArray()))
expect(featuresArray.map(f => f.get('type'))).toEqual([
'gene',
'cDNA_match',
'match',
])
const aln = featuresArray[1]!.toJSON()
expect([aln.start, aln.end]).toEqual([999, 5000])
expect(aln.subfeatures!.map(f => [f.type, f.start, f.end])).toEqual([
['cDNA_match', 999, 1200],
['cDNA_match', 1999, 2300],
['cDNA_match', 4499, 5000],
])
expect(featuresArray[2]!.toJSON().subfeatures).toEqual([])
})
})require.resolve for localPath keeps the path relative to the test file
rather than the working directory. getFeatures returns an rxjs Observable,
so firstValueFrom(obs.pipe(toArray())) turns the stream into a promise of an
array. Snapshot f.toJSON() to lock the whole shape; assert on specific fields
when the point of the test is one of them, as the second block does.
Model and session tests
In the jbrowse-components repository, createTestSession from
@jbrowse/web/testUtils builds a full root model with the core plugins and a
main-thread RPC driver, so you can exercise session actions, views, widgets, and
display models without a browser. Mock the worker factory, since jsdom has no
real workers:
import { getConfAssemblyNamesOrNone } from '@jbrowse/core/util/tracks'
import { createTestSession } from '@jbrowse/web/testUtils'
import { doSubmit } from './components/doSubmit.ts'
import type { AddTrackModel } from './model.ts'
jest.mock('@jbrowse/web/makeWorkerInstance', () => () => {})
function addAsm(session: ReturnType<typeof createTestSession>, name: string) {
session.addAssemblyConf({
name,
sequence: {
trackId: `ref-${name}`,
type: 'ReferenceSequenceTrack',
adapter: {
type: 'FromConfigSequenceAdapter',
features: [
{
refName: 'ctg',
uniqueId: name,
start: 0,
end: 10,
seq: 'acgtacgtac',
},
],
},
},
})
}
test('adding a track for an assembly not open in the view notifies the user', () => {
const session = createTestSession()
addAsm(session, 'asmA')
addAsm(session, 'asmB')
const view = session.addView('LinearGenomeView', {
displayedRegions: [
{ assemblyName: 'asmA', refName: 'ctg', start: 0, end: 10 },
],
})
const widget = session.addWidget('AddTrackWidget', 'addTrackWidget', {
view: view.id,
}) as AddTrackModel
widget.setTrackData({ uri: 'foo.bam', locationType: 'UriLocation' })
widget.setAssembly('asmB')
doSubmit({ model: widget })
// track is still added to the session...
expect(
session.tracks.some(t => getConfAssemblyNamesOrNone(t)[0] === 'asmB'),
).toBe(true)
// ...but not shown in the asmA view, and the user is told why
expect(view.tracks.length).toBe(0)
expect(
session.snackbarMessages.some(
m => m.level === 'warning' && m.message.includes('asmB'),
),
).toBe(true)
})createTestSession accepts sessionSnapshot, jbrowseConfig, adminMode, and
preloaded runtimePlugins, and returns the session model, so addView,
addWidget, showWidget, and addSessionTrackConf are all available. To test
a custom plugin's pluggable elements, pass it via runtimePlugins.
A view you add afterwards has no width, and view.width throws. There is no
layout in jsdom, so nothing sizes a view on its own: createTestSession sets
800px on the views your sessionSnapshot declares, and only those. A view from
a later session.addView(...) is unsized, and the getter throws
width undefined, make sure to check for model.initialized the moment anything
reads it — which most block and coordinate logic does. Either declare the view
in the snapshot, as the component test below does, or call view.setWidth(800)
straight after adding it, as the integration tests across the repo do.
FromConfigSequenceAdapter keeps a session test off the network: the assembly's
sequence is inline, so nothing is fetched and the assembly is ready immediately.
Component tests
React components render in jsdom with @testing-library/react, as the
templates' HelloView.test.tsx does. In the jbrowse-components repository,
build a model with createTestSession, pass it to the component, and assert on
the DOM:
import { createJBrowseTheme } from '@jbrowse/core/ui'
import { createTestSession } from '@jbrowse/web/testUtils'
import { ThemeProvider } from '@mui/material'
import { fireEvent, render, screen } from '@testing-library/react'
import GridBookmarkWidget from './GridBookmarkWidget.tsx'
import type { GridBookmarkModel } from '../model.ts'
jest.mock('@jbrowse/web/makeWorkerInstance', () => () => {})
function setup() {
const session = createTestSession({
sessionSnapshot: {
views: [
{
type: 'LinearGenomeView',
bpPerPx: 1,
offsetPx: 0,
displayedRegions: [
{ assemblyName: 'volvox', refName: 'ctgA', start: 0, end: 1000 },
],
},
],
},
})
session.addHighlight({
assemblyName: 'volvox',
refName: 'ctgA',
start: 0,
end: 100,
label: 'first region',
})
session.addHighlight({
assemblyName: 'volvox',
refName: 'ctgA',
start: 200,
end: 300,
})
const widget = session.addWidget(
'GridBookmarkWidget',
'GridBookmark',
) as GridBookmarkModel
render(
<ThemeProvider theme={createJBrowseTheme()}>
<GridBookmarkWidget model={widget} />
</ThemeProvider>,
)
return { session, widget }
}
test('the list shows each highlight with its label', async () => {
setup()
expect(await screen.findByText('first region')).toBeTruthy()
expect(screen.getByText('ctgA:1..100')).toBeTruthy()
expect(screen.getByText('Add label...')).toBeTruthy()
})
test('a click on a label edits it, and Enter writes it to the highlight', async () => {
const { session } = setup()
fireEvent.click(await screen.findByText('Add label...'))
const input = screen.getByRole('textbox', {
name: 'Edit label of ctgA:201..300',
})
fireEvent.change(input, { target: { value: 'second region' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(session.highlights[1]!.label).toBe('second region')
expect(screen.getByText('second region')).toBeTruthy()
})
test('the pencil edits a label, and emptying it clears it from the highlight', async () => {
const { session } = setup()
fireEvent.click(
await screen.findByRole('button', { name: 'Edit label of ctgA:1..100' }),
)
const input = screen.getByRole('textbox', {
name: 'Edit label of ctgA:1..100',
})
fireEvent.change(input, { target: { value: '' } })
fireEvent.blur(input)
expect(session.highlights[0]!.label).toBeUndefined()
})
test('the header checkbox selects every highlight for the bulk actions', async () => {
const { widget } = setup()
fireEvent.click(
await screen.findByRole('checkbox', { name: 'Select ctgA:1..100' }),
)
expect(widget.selectedHighlights).toHaveLength(1)
expect(screen.getByText('1 selected')).toBeTruthy()
const all = screen.getByRole<HTMLInputElement>('checkbox', {
name: 'Select all highlights',
})
expect(all.dataset.indeterminate).toBe('true')
fireEvent.click(all)
expect(widget.selectedHighlights).toHaveLength(2)
fireEvent.click(all)
expect(widget.selectedHighlights).toHaveLength(0)
})Wrap in a ThemeProvider built by createJBrowseTheme as that does: JBrowse
components read the JBrowse theme, not MUI's default.
Two jsdom gotchas:
Blobhas notext()method — useFileReader.readAsText.- Virtualized trees/grids need a mocked measured height to render any rows —
mock
useMeasureto return a large height.
Browser (end-to-end) tests
A template's end-to-end test, test/plugin.test.ts, serves the built bundle to
a JBrowse that test/setup.ts starts and saves screenshots under
test-screenshots/. In the jbrowse-components repository, Puppeteer tests in
products/jbrowse-web/browser-tests/ drive the built app and compare rendered
canvases against committed PNGs. Rendering is async, so never assert on a fixed
timeout; wait on a signal:
data-testid="loading-overlay"count reaching0means all tracks in a view finished loading.- The
data-display-drawnattribute (e.g. onsynteny_canvas) gates on a display'ssettledgetter: drawn and not refetching.
Run with pnpm test:browser (builds @jbrowse/web first) or
pnpm test:browser:update to refresh snapshots. See
agent-docs/reference/TEST_INFRASTRUCTURE.md for the full harness reference.
Developer mode: the checks that speak up in a built app
Some of what a display can get wrong is an ordering no type states and no
test of yours can see — a afterAttach that chains to super and so installs
every fetch autorun twice, a reload() that clears the error without
invalidating anything the fetch gate reads, two live SVG figures of one view
minting the same ids. Each of those draws a plausible picture and reports no
error.
JBrowse checks all of them at runtime and reports each as a sentence naming the
fix. In a JBrowse you build yourself the report is a console.error; in a
production build of somebody else's app — which is where your plugin usually
runs — nothing is listening until you say so. Three things turn it on:
- Loading your plugin from
localhost. A plugin served from your own machine into a deployed app can only be one under development, so this needs nothing from you. localStorage.jbrowseDeveloperMode = 1, then reload. Works on any deployed JBrowse, including one you do not own.configuration.preferences.developerModein a site'sconfig.json, for a deployment that is running a plugin under development.
A violation then appears as a warning notification in the session the broken display is in, alongside the console message. The notification text gives the fix and states which of the three turned it on, because the notice is about your code rather than about the reader's data.
If you are building your own chrome rather than using a JBrowse app, the
notification needs a <Snackbar session={session} /> somewhere in your tree —
without one the report still reaches the console, and nothing else.
Running tests
In a plugin template:
pnpm test- the vitest unit tests.pnpm test:e2e- build the bundle and run the Puppeteer test against a nightly JBrowse.
In the jbrowse-components repository:
pnpm test <directory>- Jest for a subtree (prefer over the full suite while iterating).pnpm test:browser- build and run the Puppeteer suite.
See also
- Developer guide: Writing a plugin
- Developer guide: Custom adapters
- Developer guide: Custom widgets