balena-supervisor/test/lib/mocked-dockerode.ts
Rich Bayliss 6ef3bd2362
docker-utils: Test network gateway determination logic
Change-type: patch
Signed-off-by: Rich Bayliss <rich@balena.io>
2020-07-22 13:17:16 +01:00

57 lines
1.1 KiB
TypeScript

import * as dockerode from 'dockerode';
export interface TestData {
networks: Dictionary<any>;
images: Dictionary<any>;
}
function createMockedDockerode(data: TestData) {
const mockedDockerode = dockerode.prototype;
mockedDockerode.getNetwork = (id: string) => {
return {
inspect: async () => {
return data.networks[id];
},
} as dockerode.Network;
};
mockedDockerode.getImage = (name: string) => {
return {
inspect: async () => {
return data.images[name];
},
} as dockerode.Image;
};
return mockedDockerode;
}
export async function testWithData(
data: Partial<TestData>,
test: () => Promise<any>,
) {
const mockedData: TestData = {
...{
networks: {},
images: {},
containers: {},
},
...data,
};
// grab the original prototype...
const basePrototype = dockerode.prototype;
// @ts-expect-error setting a RO property
dockerode.prototype = createMockedDockerode(mockedData);
try {
// run the test...
await test();
} finally {
// reset the original prototype...
// @ts-expect-error setting a RO property
dockerode.prototype = basePrototype;
}
}