Skip to content

Commit fa44bf6

Browse files
committed
chore(frontend): integrate MSW for Vitest Browser Mode
FIXME: currently does not work, see angular/angular-cli#32523
1 parent cd26e0c commit fa44bf6

9 files changed

Lines changed: 615 additions & 196 deletions

File tree

‎contenttree-frontend/package-lock.json‎

Lines changed: 503 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎contenttree-frontend/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
"angular-eslint": "21.4.0",
3939
"eslint": "^10.4.1",
4040
"jsdom": "^28.0.0",
41+
"msw": "^2.14.6",
4142
"openapi-typescript": "^7.13.0",
4243
"prettier": "^3.8.1",
4344
"typescript": "~5.9.2",

‎contenttree-frontend/src/app/tree-page/tree-page.service.spec.ts‎

Lines changed: 31 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import { provideHttpClient } from '@angular/common/http';
2-
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
31
import { TestBed } from '@angular/core/testing';
2+
import { http, HttpResponse } from 'msw';
3+
import { test as it } from '../../test-utils/msw-test';
44
import {
55
ContentRespDto,
6-
TREE_API_BASE_URL,
6+
TREE_API_BASE_PATH,
77
TreeApiService,
88
TreeNodeRespDTO,
99
} from '../api/tree-api.service';
@@ -14,7 +14,6 @@ describe('TreePageService', () => {
1414
let treeApiService: TreeApiService;
1515
let treePageService: TreePageService;
1616
let errorService: ErrorService;
17-
let httpTesting: HttpTestingController;
1817

1918
const testFlatNodes: TreeNodeRespDTO[] = [
2019
{ id: 1, name: 'Root node' },
@@ -27,61 +26,48 @@ describe('TreePageService', () => {
2726
};
2827

2928
beforeEach(() => {
30-
TestBed.configureTestingModule({
31-
providers: [provideHttpClient(), provideHttpClientTesting()],
32-
});
29+
TestBed.configureTestingModule({});
3330

34-
httpTesting = TestBed.inject(HttpTestingController);
3531
treeApiService = TestBed.inject(TreeApiService);
3632
treePageService = TestBed.inject(TreePageService);
3733
errorService = TestBed.inject(ErrorService);
3834
});
3935

4036
describe('rootNode and contentForSelectedNode', () => {
41-
it('should load a one-node tree with content', async () => {
42-
await withMockData({ flatNodes: [{ id: 1, name: 'dummy name' }], content }, () => {
43-
expect(treePageService.rootNode()).toHaveProperty('id', 1);
44-
expect(treePageService.contentForSelectedNode.value()).toEqual(content);
45-
});
46-
});
37+
it('should load a one-node tree with content', async ({ worker }) => {
38+
worker.use(
39+
http.get(TREE_API_BASE_PATH, () => HttpResponse.json([{ id: 1, name: 'dummy name' }])),
40+
http.get(`${TREE_API_BASE_PATH}/content/:id`, ({ params }) => {
41+
expect(params['id']).toEqual('1');
42+
return HttpResponse.json(content);
43+
}),
44+
);
4745

48-
it('should map child elements to parent', async () => {
49-
await withMockData({ flatNodes: testFlatNodes, content }, () => {
50-
expect(treePageService.rootNode()).toMatchObject({
51-
id: 1,
52-
children: [
53-
expect.objectContaining({ id: 2, children: [expect.objectContaining({ id: 4 })] }),
54-
expect.objectContaining({ id: 3 }),
55-
],
56-
});
57-
});
46+
expect(treePageService.rootNode()).toHaveProperty('id', 1);
47+
expect(treePageService.contentForSelectedNode.value()).toEqual(content);
5848
});
5949

60-
it('should return null if there are no elements', async () => {
61-
await withMockData({ flatNodes: [], content: null }, () => {
62-
expect(treePageService.rootNode()).toBeNullable();
63-
expect(treePageService.contentForSelectedNode.value()).toBeNullable();
50+
it('should map child elements to parent', async () => {
51+
expect(treePageService.rootNode()).toMatchObject({
52+
id: 1,
53+
children: [
54+
expect.objectContaining({ id: 2, children: [expect.objectContaining({ id: 4 })] }),
55+
expect.objectContaining({ id: 3 }),
56+
],
6457
});
6558
});
6659

67-
const withMockData = async (
68-
mockData: { flatNodes: TreeNodeRespDTO[]; content: ContentRespDto | null },
69-
callback: () => void,
70-
) => {
71-
TestBed.tick();
72-
httpTesting.expectOne({ method: 'GET', url: TREE_API_BASE_URL }).flush(mockData.flatNodes);
73-
await vi.waitUntil(() => treePageService.flatNodes.hasValue());
74-
75-
if (mockData.content) {
76-
httpTesting
77-
.expectOne({ method: 'GET', url: `${TREE_API_BASE_URL}/content/1` })
78-
.flush(mockData.content);
79-
await vi.waitUntil(() => treePageService.contentForSelectedNode.hasValue());
80-
}
60+
it('should return null if there are no elements', async ({ worker }) => {
61+
worker.use(
62+
http.get(TREE_API_BASE_PATH, () => HttpResponse.json([])),
63+
http.get(`${TREE_API_BASE_PATH}/content/:id`, () => {
64+
throw new Error('Not expected to be called');
65+
}),
66+
);
8167

82-
callback();
83-
httpTesting.verify();
84-
};
68+
expect(treePageService.rootNode()).toBeNullable();
69+
expect(treePageService.contentForSelectedNode.value()).toBeNullable();
70+
});
8571
});
8672

8773
describe('moveNode', () => {

‎contenttree-frontend/src/app/tree-page/tree-toolbar/tree-troolbar.spec.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { render } from 'vitest-browser-angular';
22
import { page, userEvent } from 'vitest/browser';
3-
import { MockTreeApiService } from '../../../test-utils/mock-factory';
4-
import { treeApiServiceMockDataForHappyCase } from '../../../test-utils/test-data';
3+
import { test as it } from '../../../test-utils/msw-test';
54
import { TreeApiService } from '../../api/tree-api.service';
65
import { TreePageService } from '../tree-page.service';
76
import { TreeToolbar } from '../tree-toolbar/tree-toolbar';
@@ -12,15 +11,8 @@ describe('TreeToolbar', () => {
1211
beforeEach(async () => {
1312
vi.useFakeTimers();
1413

15-
// See reasoning about network mocking in `mock-factory.ts`.
1614
const screen = await render(TreeToolbar, {
17-
componentProviders: [
18-
TreePageService,
19-
{
20-
provide: TreeApiService,
21-
useValue: new MockTreeApiService(treeApiServiceMockDataForHappyCase),
22-
},
23-
],
15+
componentProviders: [TreePageService, TreeApiService],
2416
});
2517

2618
treePageService = screen.fixture.debugElement.injector.get(TreePageService);

‎contenttree-frontend/src/app/tree-page/tree/tree.spec.ts‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,16 @@
11
import { render } from 'vitest-browser-angular';
22
import { page } from 'vitest/browser';
3-
import { MockTreeApiService } from '../../../test-utils/mock-factory';
4-
import { treeApiServiceMockDataForHappyCase } from '../../../test-utils/test-data';
3+
import { test as it } from '../../../test-utils/msw-test';
54
import { TreeApiService } from '../../api/tree-api.service';
65
import { TreePageService } from '../tree-page.service';
76
import { Tree } from './tree';
87

98
describe('Tree', () => {
109
let treePageService: TreePageService;
11-
const mockTreeApiService = new MockTreeApiService(treeApiServiceMockDataForHappyCase);
1210

1311
beforeEach(async () => {
14-
// See reasoning about network mocking in `mock-factory.ts`.
1512
const screen = await render(Tree, {
16-
componentProviders: [
17-
TreePageService,
18-
{
19-
provide: TreeApiService,
20-
useValue: mockTreeApiService,
21-
},
22-
],
13+
componentProviders: [TreePageService, TreeApiService],
2314
});
2415

2516
treePageService = screen.fixture.debugElement.injector.get(TreePageService);
@@ -66,8 +57,6 @@ describe('Tree', () => {
6657
.getByRole('button', { name: 'Grandchild node', exact: true })
6758
.dropTo(page.getByRole('button', { name: 'Root node', exact: true }));
6859

69-
expect.soft(mockTreeApiService.moveNode).toHaveBeenCalledWith(4, 1);
70-
7160
// Normally the tree gets fully expanded, as the Tree component gets re-rendered.
7261
await page.getByRole('button', { name: 'Toggle Root node', exact: true }).click();
7362

‎contenttree-frontend/src/test-utils/mock-factory.ts‎

Lines changed: 0 additions & 84 deletions
This file was deleted.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { http, HttpResponse } from 'msw';
2+
import { setupWorker } from 'msw/browser';
3+
import { TREE_API_BASE_PATH, TreeNodeRespDTO } from '../app/api/tree-api.service';
4+
5+
let flatNodes: TreeNodeRespDTO[] = [
6+
{ id: 1, name: 'Root node' },
7+
{ id: 2, name: 'Child node', parentId: 1 },
8+
{ id: 3, name: 'Child node 2', parentId: 1 },
9+
{ id: 4, name: 'Grandchild node', parentId: 2 },
10+
];
11+
12+
export const worker = setupWorker(
13+
http.get(TREE_API_BASE_PATH, () => HttpResponse.json(flatNodes)),
14+
15+
http.get(`${TREE_API_BASE_PATH}/content/:id`, ({ params }) => {
16+
switch (params['id']) {
17+
case '1':
18+
return HttpResponse.json({ data: 'Content for root node' });
19+
case '2':
20+
return HttpResponse.json({ data: 'Content for child node' });
21+
case '3':
22+
return HttpResponse.json({ data: 'Content for child node 2' });
23+
case '4':
24+
return HttpResponse.json({ data: 'Content for grandchild node' });
25+
default:
26+
throw new Error(`Unexpected ID: ${params['id']}`);
27+
}
28+
}),
29+
30+
http.get(`${TREE_API_BASE_PATH}/search`, ({ request }) => {
31+
const queryParams = new URL(request.url).searchParams;
32+
33+
switch (queryParams.get('text')) {
34+
case 'Grand':
35+
return HttpResponse.json([4]);
36+
case 'NonExisting':
37+
return HttpResponse.json([]);
38+
default:
39+
throw new Error(`Unexpected text: ${queryParams.get('text')}`);
40+
}
41+
}),
42+
43+
http.post(`${TREE_API_BASE_PATH}/move`, async ({ request }) => {
44+
const queryParams = new URL(request.url).searchParams;
45+
46+
if (queryParams.get('nodeId') === '4' && queryParams.get('newParentId') === '1') {
47+
flatNodes = [
48+
{ id: 1, name: 'Root node' },
49+
{ id: 2, name: 'Child node', parentId: 1 },
50+
{ id: 3, name: 'Child node 2', parentId: 1 },
51+
{ id: 4, name: 'Grandchild node', parentId: 1 },
52+
];
53+
} else {
54+
throw new Error(
55+
`Unexpected move: ${queryParams.get('nodeId')} to ${queryParams.get('newParentId')}`,
56+
);
57+
}
58+
}),
59+
);
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { SetupWorker } from 'msw/browser';
2+
import { test as testBase } from 'vitest';
3+
import { worker } from './msw-mocks';
4+
5+
export const test = testBase.extend<{ worker: SetupWorker }>({
6+
worker: [
7+
// eslint-disable-next-line no-empty-pattern
8+
async ({}, use) => {
9+
await worker.start();
10+
await use(worker);
11+
worker.resetHandlers();
12+
},
13+
{
14+
auto: true,
15+
},
16+
],
17+
});

‎contenttree-frontend/src/test-utils/test-data.ts‎

Lines changed: 0 additions & 44 deletions
This file was deleted.

0 commit comments

Comments
 (0)