azure-devops-extension-mock
v2.1.0
Published
Jest mock for the Azure DevOps Extension SDK and REST API clients — no live Azure DevOps instance required.
Readme
azure-devops-extension-mock
Jest mock for the Azure DevOps Extension SDK and Azure DevOps Extension API. Lets you unit-test Azure DevOps web extensions without a live organization, project, or network.
Install
npm install --save-dev azure-devops-extension-mockThe package has no runtime dependencies. Requires Node.js 20.19 or newer.
Peer dependencies (you almost certainly already have them):
azure-devops-extension-api≥ 5.273azure-devops-extension-sdk≥ 4.0.2 (v5 supported)
azure-devops-extension-api v4 is not supported: the mocks import
azure-devops-extension-api/Pipelines, which only exists in v5.
The mocks themselves do not depend on any test framework. The Jest helpers
under jest-helpers/ target Jest 29 and 30.
Quick start
Mock the SDK by pointing jest's module resolver at it:
// jest.config.js
module.exports = {
preset: "ts-jest",
moduleNameMapper: {
"^azure-devops-extension-sdk$": "azure-devops-extension-mock/sdk",
},
};Use the REST client mocks in your tests via getClient:
import { getClient } from "azure-devops-extension-mock";
import { GitRestClient } from "azure-devops-extension-api/Git";
const git = getClient(GitRestClient);
const repos = await git.getRepositories();
expect(repos.length).toBeGreaterThan(0);Coverage
Every method of every REST client below is callable through getClient.
Hand-written methods return generated fixtures with the real signatures and
return types; the remaining methods resolve to undefined until you pin
them with overrides. Any other Azure DevOps client works the same way
through mockClient().
| Client | Hand-written | Stubbed | Total |
| --- | ---: | ---: | ---: |
| AccountsRestClient | 3 | 0 | 3 |
| ReportingRestClient | 13 | 0 | 13 |
| AlertRestClient | 34 | 0 | 34 |
| BuildRestClient | 99 | 0 | 99 |
| ContributionsRestClient | 4 | 0 | 4 |
| CoreRestClient | 33 | 0 | 33 |
| DashboardRestClient | 13 | 0 | 13 |
| ExtensionManagementRestClient | 26 | 0 | 26 |
| FavoriteRestClient | 10 | 0 | 10 |
| FeatureAvailabilityRestClient | 5 | 0 | 5 |
| FeatureManagementRestClient | 9 | 0 | 9 |
| FileContainerRestClient | 4 | 0 | 4 |
| GalleryRestClient | 88 | 0 | 88 |
| GitRestClient | 156 | 0 | 156 |
| GraphRestClient | 40 | 0 | 40 |
| LocationsRestClient | 10 | 0 | 10 |
| ManagementRestClient | 21 | 0 | 21 |
| NotificationRestClient | 24 | 0 | 24 |
| OperationsRestClient | 1 | 0 | 1 |
| PipelinesRestClient | 10 | 0 | 10 |
| PolicyRestClient | 12 | 0 | 12 |
| ProfileRestClient | 12 | 0 | 12 |
| ProjectAnalysisRestClient | 4 | 0 | 4 |
| ReleaseRestClient | 87 | 0 | 87 |
| ResourceUsageRestClient | 2 | 0 | 2 |
| ServiceEndpointRestClient | 27 | 0 | 27 |
| ServiceHooksRestClient | 23 | 0 | 23 |
| TaskAgentRestClient | 158 | 0 | 158 |
| TestRestClient | 77 | 0 | 77 |
| TestPlanRestClient | 48 | 0 | 48 |
| TestResultsRestClient | 140 | 0 | 140 |
| TfvcRestClient | 24 | 0 | 24 |
| WikiRestClient | 23 | 0 | 23 |
| WorkRestClient | 57 | 0 | 57 |
| WorkItemTrackingRestClient | 75 | 0 | 75 |
| WorkItemTrackingProcessRestClient | 57 | 0 | 57 |
| WorkItemTrackingProcessDefinitionsRestClient | 46 | 0 | 46 |
| All | 1475 | 0 | 1475 |
The table is generated by npm run surface, which reads the real .d.ts
declarations, and a test fails if a mock ever declares a method the real
client does not have.
Every export of the real SDK (init, ready, getUser, getHost,
getService, register, resize, tokens, theming, page/web/team/extension
context, sdkVersion, HostType, ...) is mocked in
azure-devops-extension-mock/sdk, plus the v5 enableNestedAppAuth and
disableNestedAppAuth.
API
getClient(realClientClass, overrides?)
Returns a mock instance for any Azure DevOps REST client class. Methods
with a hand-written mock return fixtures; every other method of the real
client resolves to undefined. No request is ever issued.
import { getClient } from "azure-devops-extension-mock";
import { BuildRestClient } from "azure-devops-extension-api/Build";
const build = getClient(BuildRestClient, {
queueBuild: async () => ({ id: 42, status: 2 } as any),
});
const result = await build.queueBuild({} as any, "MyProject");
expect(result.id).toBe(42);mockClient(realClientClass, overrides?, options?)
Lower-level factory used by getClient. Returns a Proxy that merges the
registered hand-written mock (if any) with the caller's overrides.
registerMockClient(realClientClass, MockClass)
Register a custom mock for a client not covered by this package. The
registered mock will be returned by all subsequent getClient calls.
getService(serviceId) / registerMockService(id, impl)
Mocks for CommonServiceIds.* services: extension data, host navigation,
page layout, location, global messages, project page. Register your own
for unknown ids.
getPageContext, getUser, getHost, …
Re-exported from azure-devops-extension-mock/sdk, matching the real SDK's
shape with randomly-generated fixture data.
Deterministic fixtures
Fixture data is random by default. Call seed to make a test run
reproducible:
import { fake } from "azure-devops-extension-mock/fixtures";
beforeEach(() => fake.seed(1234));Stateful mode
By default the mocks keep no state: an object you create with one method is
not returned by a later get or list. Turn the stateful mode on to test
flows that create, update or delete and then read back:
import { getClient, stateful } from "azure-devops-extension-mock";
import { WorkItemTrackingRestClient } from "azure-devops-extension-api/WorkItemTracking";
beforeEach(() => stateful.enable());
afterEach(() => stateful.disable());
it("reads back a work item it created", async () => {
const client = getClient(WorkItemTrackingRestClient);
const created = await client.createWorkItem(
[{ op: "add", path: "/fields/System.Title", value: "Fix login" }],
"MyProject",
"Bug"
);
const read = await client.getWorkItem(created.id);
expect(read.fields["System.Title"]).toBe("Fix login");
});stateful.enable()turns it on,stateful.reset()restores the seeded data, andstateful.disable()restores it and turns the mode off.- The mode covers
GitRestClient,WorkItemTrackingRestClientandBuildRestClient. The other clients stay stateless. - An update starts from the stored entry, so fields you do not pass keep their value. An object you create without an id gets one that no seeded entry uses.
- Not every read follows the writes. In Git, a created thread is not listed
by
getThreadsand new refs do not appear ingetBranches; reviewers, labels and statuses are shared by all pull requests. In WorkItemTracking, revisions and updates are not recorded andgetRootNodesdoes not show created nodes. In Build, tags and artifacts are shared by all builds, and settings and property bags stay stateless.
Using with jest
Two things to wire up when testing an extension:
- Redirect the SDK import in
jest.config.js(moduleNameMapper). - Load
jest-helpers/setup-globalsso the browser globals the real packages expect exist under Node.
The AMD transformer under jest-helpers/ is optional.
azure-devops-extension-api v5 is CommonJS and the transformer returns its
modules unchanged, so an existing configuration that lists it keeps working.
A ready-to-copy configuration:
module.exports = {
preset: "ts-jest",
moduleNameMapper: {
"^azure-devops-extension-sdk$": "azure-devops-extension-mock/sdk"
},
transform: {
"node_modules[\\\\/]azure-devops-extension-api[\\\\/].+\\.js$":
"azure-devops-extension-mock/jest-helpers/amd-transformer"
},
transformIgnorePatterns: ["node_modules/(?!azure-devops-extension-api)"],
setupFiles: ["azure-devops-extension-mock/jest-helpers/setup-globals"]
};This is the configuration of the example extension in
examples/consumer. CI installs the packed build into
that example and runs its tests, and a test in this repository fails if the
block above and the example's jest.config.js drift apart.
Testing extension code
Extension code calls getClient from azure-devops-extension-api. To make
that call return the mocks, replace it in the test file and keep every other
export of the real package:
import { getClient } from "azure-devops-extension-api";
import { getClient as getMockClient } from "azure-devops-extension-mock";
jest.mock("azure-devops-extension-api", () => ({
...jest.requireActual("azure-devops-extension-api"),
getClient: jest.fn()
}));
const useMockClients = (overrides: Record<string, unknown> = {}): void => {
(getClient as jest.Mock).mockImplementation(clientClass => getMockClient(clientClass, overrides));
};
beforeEach(() => useMockClients());Pin a response for one test by passing overrides:
useMockClients({ getRepositories: async () => [] });The SDK needs no such step: moduleNameMapper already points
azure-devops-extension-sdk at the mock, so SDK.ready(), SDK.getUser()
and SDK.getService() work as they are.
examples/consumer has the full working test.
By default the mocks keep no state between calls: an object you create with
one method is not returned by a later get or list. For flows that depend
on that, use overrides or turn on the stateful mode.
Fixture helpers
fake, exported from azure-devops-extension-mock/fixtures, generates the
random data and has two helpers for writing your own fixtures:
fake.helpers.distinct(length, make, ...keys)builds a list whose items never repeat the given keys. Use it for a list you look up by name:fake.helpers.distinct(3, makeTeam, team => team.name).fake.helpers.absent()stands in for a field the service leaves out, such asclosedByon an open pull request. The field reads asundefined.
Upgrading from 1.x
2.0.0 changes what some mocks return. If a test fails after upgrading, check these first; the changelog has the full list.
| Area | 1.x | 2.x |
| --- | --- | --- |
| Test result outcome | a number | the outcome name, such as "Passed" |
| Test run state | 3 | "Completed" |
| Test attachment attachmentType | "GeneralAttachment" | AttachmentType.GeneralAttachment |
| GitRestClient.getRefs | a plain array | a PagedList with continuationToken |
| GitRestClient.getCommit | no treeId | a GitCommit with treeId |
| ReleaseDefinition.environments | release environments | definition environments, without status |
| Agents inside TaskAgent requests | full agents | TaskAgentReference objects |
| Pipeline configuration.type | "yaml" | ConfigurationType.Yaml |
| Clients that had no mock | every method resolved to undefined | hand-written fixtures |
| Values under a fixed fake.seed | | differ from 1.x |
The peer range is narrower too: azure-devops-extension-api 5.273 or newer
and azure-devops-extension-sdk 4.0.2 or newer.
Contributing
npm ci
npm run lint # eslint with the typescript-eslint recommended rules
npm run format # prettier; CI runs format:check
npm test # runs jest with coverage (100% threshold enforced)
npm run build # emits dist/
npm run surface # compares the mocks with the real client declarations
npm run audit:prod # production dependency audit
npm run compat floor # installs the packed build next to the oldest supported peers
npm run example # installs the packed build into examples/consumer and runs its testsCI runs tests on Node 20, 22 and 24, checks the packed build against the
oldest and the latest supported peers and runs the example extension
(node.js.yml), weekly npm audit and Gitleaks scans (security.yml), and
CodeQL through GitHub's default code scanning setup.
CONTRIBUTING.md has the rules a change must follow.
Comparing the mocks with a real organization
The fixture values are generated, not recorded from the service.
npm run shape-diff compares the field names a real organization returns
with the ones the mocks return, for eight common list endpoints:
npm run build
AZURE_DEVOPS_ORG_URL=https://dev.azure.com/your-org \
AZURE_DEVOPS_PROJECT=YourProject \
AZURE_DEVOPS_PAT=... \
npm run shape-diffIt only issues GET requests, reads the token from the environment, and
prints field names, never values. A token with read scope is enough.
Releasing
- Update the version in
package.jsonand move theUnreleasednotes inCHANGELOG.mdunder that version. - Merge to
main, then push a tag matching the version:git tag v1.2.3 && git push origin v1.2.3. release.ymlchecks that the tag matchespackage.jsonand that the tagged commit is onmain, then lints, builds, tests, runs the compat and example checks, audits, publishes to npm with provenance via trusted publishing, and creates the GitHub release. No npm token is stored in the repository.
License
MIT — see license.
