Skip to content

Instantly share code, notes, and snippets.

@jdelibas
Created April 6, 2022 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdelibas/e7cc9874b661b14843ed33c962b8cdd7 to your computer and use it in GitHub Desktop.
Save jdelibas/e7cc9874b661b14843ed33c962b8cdd7 to your computer and use it in GitHub Desktop.
Proxyquire in typescript

proxyquire with typescript

Exmaple on how to get proxyquire working with typescript

import anyTest, { TestInterface } from 'ava';
import sinon, { SinonStub } from 'sinon';
import proxyquire from 'proxyquire';
type AxiosStub = {
get: SinonStub;
}
type Context = {
axios: AxiosStub;
fn: Function;
};
const test = anyTest as TestInterface<Context>;
test.before((t) => {
t.context.axios = {
get: sinon.stub(),
}
t.context.fn = proxyquire('./adapter', {
'axios': t.context.axios
}).default;
});
test('should correctly mock axios', async (t) => {
// Arrange
const expected = { some: 'data '}
t.context.axios.get.resolves({ data: expected });
// Act
const result = await t.context.fn();
// Assert
t.deepEqual(result, expected);
});
test('should correctly handle error', async (t) => {
// Arrange
const expected = {
instanceOf: Error,
message: 'Something failed here',
};
t.context.axios.get.rejects({ data: expected });
// Assert
await t.throwsAsync(
// Act
t.context.fn(),
expected,
);
});
import axios from 'axios';
const adapter = async () => {
try {
const { data } = await axios.get('/')
return data
} catch(err) {
throw new Error('Something failed here')
}
}
export default adapter;
import anyTest, { TestInterface } from 'ava';
import sinon, { SinonStub } from 'sinon';
import proxyquire from 'proxyquire';
type Context = {
adapterStub: SinonStub;
fn: Function;
};
const test = anyTest as TestInterface<Context>;
test.before((t) => {
t.context.adapterStub = sinon.stub()
t.context.fn = proxyquire('./index', {
'./adapter': {
default: t.context.adapterStub
},
}).default;
});
test('should correctly mock the adapter call', async (t) => {
// Arrange
const expected = { some: 'data '}
t.context.adapterStub.resolves({ data: expected });
// Act
const result = await t.context.fn();
// Assert
t.deepEqual(result, expected);
});
import adapter from './adapter';
const demo = async () => {
const { data } = await adapter();
return data;
}
export default demo;
{
"name": "proxyquire-typescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "tsc && nyc ava"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "14.14.22",
"@types/proxyquire": "1.3.28",
"@types/sinon": "10.0.2",
"ava": "3.5.0",
"nock": "13.0.5",
"nyc": "15.1.0",
"proxyquire": "2.1.3",
"sinon": "11.1.1",
"ts-loader": "8.0.14",
"ts-node": "9.1.1",
"typescript": "4.1.3"
},
"dependencies": {
"axios": "0.26.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment