msw#rest TypeScript Examples
The following examples show how to use
msw#rest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tests-utils.mock-server.ts From jitsu with MIT License | 7 votes |
mockEndpointsCatalog = {
destination_test: {
responseData: mockDestinationTest,
requestFactory: mockData =>
rest.post("*/destinations/test", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
destinations_post: {
responseData: {
status: "ok",
},
requestFactory: mockData =>
rest.post("*/destinations", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
sources_post: {
responseData: {
status: "ok",
},
requestFactory: mockData =>
rest.post("*/configurations/sources*", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
} as const
Example #2
Source File: TaxonomicFilter.stories.tsx From posthog-foss with MIT License | 6 votes |
mockGetPropertyDefinitions = (
handler: ResponseResolver<
RestRequest<GetPropertyDefinitionsRequest, any>,
RestContext,
GetPropertyDefinitionsResponse
>
) =>
rest.get<GetPropertyDefinitionsRequest, GetPropertyDefinitionsResponse>(
'/api/projects/@current/property_definitions',
handler
)
Example #3
Source File: ProductionApi.test.ts From backstage with Apache License 2.0 | 6 votes |
describe('The production Airbrake API', () => {
const productionApi = new ProductionAirbrakeApi(localDiscoveryApi);
const worker = setupServer();
setupRequestMockHandlers(worker);
it('fetches groups using the provided project ID', async () => {
worker.use(
rest.get(
'http://localhost:7007/api/airbrake/api/v4/projects/123456/groups',
(_, res, ctx) => {
return res(ctx.status(200), ctx.json(mockGroupsData));
},
),
);
const groups = await productionApi.fetchGroups('123456');
expect(groups).toStrictEqual(mockGroupsData);
});
it('throws if fetching groups was unsuccessful', async () => {
worker.use(
rest.get(
'http://localhost:7007/api/airbrake/api/v4/projects/123456/groups',
(_, res, ctx) => {
return res(ctx.status(500));
},
),
);
await expect(productionApi.fetchGroups('123456')).rejects.toThrow();
});
});
Example #4
Source File: utils.ts From frontend with BSD 3-Clause "New" or "Revised" License | 6 votes |
export function mockAPI (url: string, method: HTTPMethods): RequestHandler {
return rest[method](url, (req, res, ctx) =>
loadFixture(req.url.pathname, req.method).then(data => res(
ctx.status(200),
ctx.json(data)
))
)
}
Example #5
Source File: budget.api.mocked.it.ts From budget-angular with GNU General Public License v3.0 | 6 votes |
createGetBudgetsStub = () => {
return rest.get("/api/budgets", (req, res, ctx) => {
const query = req.url.searchParams;
const month = parseInt(query.get("month"));
const year = parseInt(query.get("year"));
if (month > 0 && month <= 12 && year > 0) {
return res(
ctx.json([
{
id: 1,
accountId: 1,
period: {
month: 12,
year: 2020,
},
},
])
);
} else {
return res(ctx.json([]));
}
});
}
Example #6
Source File: testServer.ts From raspiblitz-web with MIT License | 6 votes |
server = setupServer(
rest.get("*", (req, res, ctx) => {
console.error(`Add request handler for ${req.url.toString()}`);
return res(
ctx.status(500),
ctx.json({ error: "Missing request handler." })
);
})
)
Example #7
Source File: tests-utils.mock-server.ts From jitsu with MIT License | 6 votes |
mockObligatoryEndpoints = {
configuration: {
responseData: mockConfiguration,
requestFactory: (mockData: unknown) =>
rest.get("*/system/configuration", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
userInfo: {
responseData: mockUserInfo,
requestFactory: (mockData: unknown) =>
rest.get(`*/users/info*`, (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
statistics: {
responseData: mockStatistics,
requestFactory: (mockData: unknown) =>
rest.get("*/statistics*", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
onboarded: {
responseData: { completed: true },
requestFactory: (mockData: unknown) =>
rest.get("*/configurations/onboarding_tour_completed*", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
api_keys: {
responseData: mockApiKeys,
requestFactory: mockData =>
rest.get("*/api_keys*", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
destinations_get: {
responseData: mockDestinationsList,
requestFactory: mockData =>
rest.get("*/destinations", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
sources_get: {
responseData: mockSources,
requestFactory: mockData =>
rest.get("*/configurations/sources*", (req, res, ctx) => {
return res(ctx.json(mockData))
}),
},
} as const
Example #8
Source File: handlers.ts From mitojs with MIT License | 6 votes |
handlers = [
// rest.get('/error/upload.gif', (req, res, ctx) => {
// return res(ctx.jons)
// }),
rest.post('/error/upload', (req, res, ctx) => {
return res(
ctx.json({
message: '上传成功'
})
)
}),
rest.get('/normal', (req, res, ctx) => {
return res(
ctx.json({
code: 200,
message: '这是正常接口'
})
)
})
]
Example #9
Source File: Bookings.test.tsx From office-booker with MIT License | 6 votes |
test('Can cancel booking', async () => {
const office = createFakeOffice();
const user = createFakeSystemAdminUser([office]);
const booking = createFakeBooking({ office, user: '[email protected]' });
const deleteReq = jest.fn();
server.use(
mockGetOffices([office]),
mockGetBookings([booking]),
rest.delete(`/api/bookings/:bookingId`, (req, res, ctx) => {
deleteReq({ bookingId: req.params.bookingId, user: req.url.searchParams.get('user') });
return res(ctx.status(200));
})
);
render(
<TestContext user={user}>
<Bookings />
</TestContext>
);
const cancelButton = await screen.findByRole('button', { name: 'Cancel' });
fireEvent.click(cancelButton);
const dialog = await screen.findByRole('dialog');
queries.getByText(dialog, 'Are you sure you want to cancel this booking?');
fireEvent.click(queries.getByRole(dialog, 'button', { name: 'Yes' }));
await screen.findByText('Booking cancelled');
expect(deleteReq).toHaveBeenCalledWith({ bookingId: booking.id, user: booking.user });
});
Example #10
Source File: json-rpc-server.mock.ts From cloud-cryptographic-wallet with MIT License | 6 votes |
export function makeHandler(
rpcUrl: string,
mock: Mock
): RestHandler<MockedRequest<DefaultRequestBody>> {
const handler = rest.post<{ id: string; method: string }>(
rpcUrl,
(req, res, ctx) => {
const { id, method } = req.body;
if (method === mock.method) {
return res(
ctx.json({
id,
result: mock.result,
})
);
}
return res(ctx.json({}));
}
);
return handler;
}
Example #11
Source File: LoginModal.spec.tsx From slice-machine with Apache License 2.0 | 6 votes |
server = setupServer(
rest.post("/api/auth/start", (_, res, ctx) => {
return res(ctx.json({}));
}),
rest.post("/api/auth/status", (_, res, ctx) => {
return res(
ctx.json({
status: "ok", //"error" | "ok" | "pending";
userId: "foo",
})
);
})
)
Example #12
Source File: EventSelect.stories.tsx From posthog-foss with MIT License | 5 votes |
mockGetEventDefinitions = (
handler: ResponseResolver<RestRequest<GetEventDefinitionsRequest, any>, RestContext, GetEventDefinitionsResponse>
) =>
rest.get<GetEventDefinitionsRequest, GetEventDefinitionsResponse>(
'/api/projects/:projectId/event_definitions',
handler
)
Example #13
Source File: product.test.ts From Fashionista with MIT License | 5 votes |
server = setupServer(
rest.get(/\/catalog$/, (_, res, ctx) => {
return res(ctx.json(mockedProducts));
})
)
Example #14
Source File: handlers.ts From react-query-auth with MIT License | 5 votes |
handlers = [
rest.get('/auth/me', (req, res, ctx) => {
const user = getUser(req.headers.get('Authorization'));
if (user) {
return res(ctx.delay(1000), ctx.json(user));
}
return res(
ctx.delay(1000),
ctx.status(401),
ctx.json({ message: 'Unauthorized' })
);
}),
rest.post('/auth/login', (req, res, ctx) => {
const parsedBody = JSON.parse(req.body as string) as User;
const user = getUser(parsedBody.email);
if (user) {
return res(
ctx.delay(1000),
ctx.json({
jwt: user.email,
user,
})
);
} else {
return res(
ctx.delay(1000),
ctx.status(401),
ctx.json({ message: 'Unauthorized' })
);
}
}),
rest.post('/auth/register', (req, res, ctx) => {
const parsedBody = JSON.parse(req.body as string) as User;
const user = getUser(parsedBody?.email);
if (!user && parsedBody) {
const newUser = setUser(parsedBody);
if (newUser) {
return res(
ctx.delay(1000),
ctx.json({
jwt: newUser.email,
user: getUser(newUser.email),
})
);
}
return res(
ctx.delay(1000),
ctx.status(403),
ctx.json({ message: 'Forbidden User' })
);
} else {
return res(
ctx.delay(1000),
ctx.status(400),
ctx.json({ message: 'The user already exists!' })
);
}
}),
]
Example #15
Source File: manifest.test.ts From backstage with Apache License 2.0 | 5 votes |
describe('Release Manifests', () => {
const worker = setupServer();
setupRequestMockHandlers(worker);
describe('getManifestByVersion', () => {
it('should return a list of packages in a release', async () => {
worker.use(
rest.get('*/v1/releases/0.0.0/manifest.json', (_, res, ctx) =>
res(
ctx.status(200),
ctx.json({
packages: [{ name: '@backstage/core', version: '1.2.3' }],
}),
),
),
rest.get('*/v1/releases/999.0.1/manifest.json', (_, res, ctx) =>
res(ctx.status(404), ctx.json({})),
),
);
const pkgs = await getManifestByVersion({ version: '0.0.0' });
expect(pkgs.packages).toEqual([
{
name: '@backstage/core',
version: '1.2.3',
},
]);
await expect(
getManifestByVersion({ version: '999.0.1' }),
).rejects.toThrow('No release found for 999.0.1 version');
});
});
describe('getManifestByReleaseLine', () => {
it('should return a list of packages in a release', async () => {
worker.use(
rest.get(
'https://versions.backstage.io/v1/tags/main/manifest.json',
(_, res, ctx) =>
res(
ctx.status(200),
ctx.json({
packages: [{ name: '@backstage/core', version: '1.2.3' }],
}),
),
),
rest.get(
'https://versions.backstage.io/v1/tags/foo/manifest.json',
(_, res, ctx) => res(ctx.status(404), ctx.json({})),
),
);
const pkgs = await getManifestByReleaseLine({ releaseLine: 'main' });
expect(pkgs.packages).toEqual([
{
name: '@backstage/core',
version: '1.2.3',
},
]);
await expect(
getManifestByReleaseLine({ releaseLine: 'foo' }),
).rejects.toThrow("No 'foo' release line found");
});
});
});
Example #16
Source File: use-user.spec.tsx From frontend with BSD 3-Clause "New" or "Revised" License | 5 votes |
function mockLogin (statusCode: number, response: Object = {}): void {
mockServer.use(
rest.post('http://localhost/p/login', (req, res, ctx) => {
return res(ctx.status(statusCode), ctx.json(response))
})
)
}
Example #17
Source File: handlers.ts From gear-js with GNU General Public License v3.0 | 5 votes |
handlers = [
rest.get(DEFAULT_NODES_URL, (_req, res, ctx) => {
return res(ctx.json(sidebarNodes));
}),
]
Example #18
Source File: handlers.ts From office-booker with MIT License | 5 votes |
mockGetConfig = (config: Config) =>
rest.get('/api/config', (req, res, ctx) => res(ctx.json(config)))
Example #19
Source File: handlers.ts From pancake-toolkit with GNU General Public License v3.0 | 5 votes |
handlers = [
rest.get(`${profileApi}/api/users/${existingAddress1}`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
username: "Cheems",
})
);
}),
rest.get(`${profileApi}/api/users/${nonexistentAddress}`, (req, res, ctx) => {
return res(ctx.status(404), ctx.json({ error: { message: "Entity not found." } }));
}),
rest.get(`${IPFS_GATEWAY}/ipfs/QmYsTqbmGA3H5cgouCkh8tswJAQE1AsEko9uBZX9jZ3oTC/sleepy.json`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
name: "Sleepy",
description: "Aww, looks like eating pancakes all day is tough work. Sweet dreams!",
image: "ipfs://QmYD9AtzyQPjSa9jfZcZq88gSaRssdhGmKqQifUDjGFfXm/sleepy.png",
attributes: {
bunnyId: "5",
},
})
);
}),
subgraph.query("getUser", (req, res, ctx) => {
const address = req.variables.id;
if (address === existingAddress1) {
return res(
ctx.data({
user: {
points: [
{
id: existingAddress1,
campaignId: "511080000",
points: 200,
},
{
id: existingAddress1,
campaignId: "512010010",
points: 500,
},
{
id: existingAddress1,
campaignId: "511090000",
points: 100,
},
],
},
})
);
}
if (address === existingAddress2) {
return res(
ctx.data({
user: {
points: [],
},
})
);
}
// Address does not exists
return res(
ctx.data({
user: null,
})
);
}),
]
Example #20
Source File: CreateCustomTypeModal.spec.tsx From slice-machine with Apache License 2.0 | 5 votes |
server = setupServer(
rest.post("/api/custom-types/save", (_, res, ctx) => {
return res(ctx.json({}));
})
)
Example #21
Source File: AwsS3UrlReader.test.ts From backstage with Apache License 2.0 | 4 votes |
describe('AwsS3UrlReader', () => {
const worker = setupServer();
setupRequestMockHandlers(worker);
const createReader = (config: JsonObject): UrlReaderPredicateTuple[] => {
return AwsS3UrlReader.factory({
config: new ConfigReader(config),
logger: getVoidLogger(),
treeResponseFactory,
});
};
it('creates a dummy reader without the awsS3 field', () => {
const entries = createReader({
integrations: {},
});
expect(entries).toHaveLength(1);
});
it('creates a reader with credentials correctly configured', () => {
const awsS3Integrations = [];
awsS3Integrations.push({
host: 'amazonaws.com',
accessKeyId: 'fakekey',
secretAccessKey: 'fakekey',
});
const entries = createReader({
integrations: {
awsS3: awsS3Integrations,
},
});
expect(entries).toHaveLength(1);
});
it('creates a reader with default credentials provider', () => {
const awsS3Integrations = [];
awsS3Integrations.push({
host: 'amazonaws.com',
});
const entries = createReader({
integrations: {
awsS3: awsS3Integrations,
},
});
expect(entries).toHaveLength(1);
});
describe('predicates', () => {
const readers = createReader({
integrations: {
awsS3: [{}],
},
});
const predicate = readers[0].predicate;
it('returns true for the correct aws s3 storage host', () => {
expect(
predicate(new URL('https://test-bucket.s3.us-east-2.amazonaws.com')),
).toBe(true);
});
it('returns true for a url with the full path and the correct host', () => {
expect(
predicate(
new URL(
'https://test-bucket.s3.us-east-2.amazonaws.com/team/service/catalog-info.yaml',
),
),
).toBe(true);
});
it('returns false for an incorrect host', () => {
expect(predicate(new URL('https://amazon.com'))).toBe(false);
});
it('returns false for a completely different host', () => {
expect(predicate(new URL('https://storage.cloud.google.com'))).toBe(
false,
);
});
it("returns true for a url with a bucket with '.'", () => {
expect(
predicate(
new URL(
'https://test.bucket.s3.us-east-2.amazonaws.com/team/service/catalog-info.yaml',
),
),
).toBe(true);
});
});
describe('read', () => {
const [{ reader }] = createReader({
integrations: {
awsS3: [
{
host: 'amazonaws.com',
accessKeyId: 'fake-access-key',
secretAccessKey: 'fake-secret-key',
},
],
},
});
beforeEach(() => {
worker.use(
rest.get(
'https://test-bucket.s3.amazonaws.com/awsS3-mock-object.yaml',
(_, res, ctx) =>
res(
ctx.status(200),
ctx.set('ETag', '123abc'),
ctx.body('site_name: Test'),
),
),
);
});
it('returns contents of an object in a bucket', async () => {
const response = await reader.read(
'https://test-bucket.s3.us-east-2.amazonaws.com/awsS3-mock-object.yaml',
);
expect(response.toString().trim()).toBe('site_name: Test');
});
it('rejects unknown targets', async () => {
await expect(
reader.read(
'https://test-bucket.s3.us-east-2.NOTamazonaws.com/file.yaml',
),
).rejects.toThrow(
Error(
`Could not retrieve file from S3; caused by Error: Invalid AWS S3 URL https://test-bucket.s3.us-east-2.NOTamazonaws.com/file.yaml`,
),
);
});
});
describe('readUrl', () => {
const [{ reader }] = createReader({
integrations: {
awsS3: [
{
host: 'amazonaws.com',
accessKeyId: 'fake-access-key',
secretAccessKey: 'fake-secret-key',
},
],
},
});
beforeEach(() => {
worker.use(
rest.get(
'https://test-bucket.s3.amazonaws.com/awsS3-mock-object.yaml',
(_, res, ctx) =>
res(
ctx.status(200),
ctx.set('ETag', '123abc'),
ctx.body('site_name: Test'),
),
),
);
});
it('returns contents of an object in a bucket via buffer', async () => {
const response = await reader.readUrl!(
'https://test-bucket.s3.us-east-2.amazonaws.com/awsS3-mock-object.yaml',
);
expect(response.etag).toBe('123abc');
const buffer = await response.buffer();
expect(buffer.toString().trim()).toBe('site_name: Test');
});
it('returns contents of an object in a bucket via stream', async () => {
const response = await reader.readUrl!(
'https://test-bucket.s3.us-east-2.amazonaws.com/awsS3-mock-object.yaml',
);
expect(response.etag).toBe('123abc');
const fromStream = await getRawBody(response.stream!());
expect(fromStream.toString().trim()).toBe('site_name: Test');
});
it('rejects unknown targets', async () => {
await expect(
reader.readUrl!(
'https://test-bucket.s3.us-east-2.NOTamazonaws.com/file.yaml',
),
).rejects.toThrow(
Error(
`Could not retrieve file from S3; caused by Error: Invalid AWS S3 URL https://test-bucket.s3.us-east-2.NOTamazonaws.com/file.yaml`,
),
);
});
});
describe('readUrl towards custom host', () => {
const [{ reader }] = createReader({
integrations: {
awsS3: [
{
host: 'localhost:4566',
accessKeyId: 'fake-access-key',
secretAccessKey: 'fake-secret-key',
endpoint: 'http://localhost:4566',
s3ForcePathStyle: true,
},
],
},
});
beforeEach(() => {
worker.use(
rest.get(
'http://localhost:4566/test-bucket/awsS3-mock-object.yaml',
(_, res, ctx) =>
res(
ctx.status(200),
ctx.set('ETag', '123abc'),
ctx.body('site_name: Test'),
),
),
);
});
it('returns contents of an object in a bucket via buffer', async () => {
const response = await reader.readUrl!(
'http://localhost:4566/test-bucket/awsS3-mock-object.yaml',
);
expect(response.etag).toBe('123abc');
const buffer = await response.buffer();
expect(buffer.toString().trim()).toBe('site_name: Test');
});
});
describe('readUrl with etag', () => {
const [{ reader }] = createReader({
integrations: {
awsS3: [
{
host: 'amazonaws.com',
accessKeyId: 'fake-access-key',
secretAccessKey: 'fake-secret-key',
},
],
},
});
beforeEach(() => {
worker.use(
rest.get(
'https://test-bucket.s3.amazonaws.com/awsS3-mock-object.yaml',
(_, res, ctx) => res(ctx.status(304)),
),
);
});
it('returns contents of an object in a bucket', async () => {
await expect(
reader.readUrl!(
'https://test-bucket.s3.us-east-2.amazonaws.com/awsS3-mock-object.yaml',
{
etag: '123abc',
},
),
).rejects.toThrow(NotModifiedError);
});
});
describe('readTree', () => {
let awsS3UrlReader: AwsS3UrlReader;
beforeAll(() => {
const object: aws.S3.Types.Object = {
Key: 'awsS3-mock-object.yaml',
};
const objectList: aws.S3.ObjectList = [object];
const output: aws.S3.Types.ListObjectsV2Output = {
Contents: objectList,
};
AWSMock.setSDKInstance(aws);
AWSMock.mock('S3', 'listObjectsV2', output);
AWSMock.mock(
'S3',
'getObject',
Buffer.from(
require('fs').readFileSync(
path.resolve(
__dirname,
'__fixtures__/awsS3/awsS3-mock-object.yaml',
),
),
),
);
const s3 = new aws.S3();
awsS3UrlReader = new AwsS3UrlReader(
new AwsS3Integration(
readAwsS3IntegrationConfig(
new ConfigReader({
host: '.amazonaws.com',
accessKeyId: 'fake-access-key',
secretAccessKey: 'fake-secret-key',
}),
),
),
{ s3, treeResponseFactory },
);
});
it('returns contents of an object in a bucket', async () => {
const response = await awsS3UrlReader.readTree(
'https://test.s3.us-east-2.amazonaws.com',
);
const files = await response.files();
const body = await files[0].content();
expect(body.toString().trim()).toBe('site_name: Test');
});
});
});