homehub/packages/homehub_core/tests/lib/rpc.spec.js

118 lines
2.9 KiB
JavaScript
Raw Normal View History

2021-08-26 10:33:15 +00:00
import * as RPCLib from 'src/lib/rpc';
describe('src/lib/rpc', () => {
describe('callMethod', () => {
beforeEach(() => {
spyOn(window, 'fetch');
});
it('formats and sends a POST request to the backend RPC URL', async () => {
// Given
window.fetch.and.resolveTo({
ok: true,
status: 200,
statusText: 'OK',
json: jasmine.createSpy().and.resolveTo({
result: 'ok',
}),
});
// When
await RPCLib.callMethod('testing', ['spam']);
// Then
expect(window.fetch).toHaveBeenCalledWith('/backend/rpc', {
method: 'POST',
body: jasmine.any(String),
headers: {
'Content-Type': 'application/json',
},
});
const callArgs = window.fetch.calls.argsFor(0);
const body = JSON.parse(callArgs[1].body);
expect(body.jsonrpc).toEqual('2.0');
expect(body.method).toEqual('testing');
expect(body.params).toEqual(['spam']);
expect(body.id).toBeUUIDv4();
});
it('formats a notification call', async () => {
// Given
window.fetch.and.resolveTo({
ok: true,
status: 200,
statusText: 'OK',
json: jasmine.createSpy().and.resolveTo({
result: 'ok',
}),
});
// When
await RPCLib.callMethod('testing', ['spam'], true);
// Then
const callArgs = window.fetch.calls.argsFor(0);
const body = JSON.parse(callArgs[1].body);
expect(body.id).not.toBeDefined();
});
it('returns an error is the response was not OK', async () => {
// Given
window.fetch.and.resolveTo({
ok: false,
status: 400,
statusText: 'Bad Request',
});
// When
const result = await RPCLib.callMethod('testing');
// Then
expect(result).not.toContain('data');
expect(result.error).toMatch('HTTP 400 Bad Request');
});
it('returns an error is the response was a JSONRPC error', async () => {
// Given
window.fetch.and.resolveTo({
ok: true,
status: 200,
statusText: 'OK',
json: jasmine.createSpy().and.resolveTo({
error: {
message: 'Internal error',
data: 'Test',
},
}),
});
// When
const result = await RPCLib.callMethod('testing');
// Then
expect(result).not.toContain('data');
expect(result.error).toMatch('RPC Error: Internal error Test');
});
it('returns an result is the response was successful', async () => {
// Given
window.fetch.and.resolveTo({
ok: true,
status: 200,
statusText: 'OK',
json: jasmine.createSpy().and.resolveTo({
result: 'ok',
}),
});
// When
const result = await RPCLib.callMethod('testing');
// Then
expect(result.data).toEqual('ok');
expect(result).not.toContain('error');
});
});
});