Skip to content

Instantly share code, notes, and snippets.

@addityasingh
Created June 13, 2019 14:33
Show Gist options
  • Save addityasingh/be82e4d1e9bbac528c0f002ecd9a026b to your computer and use it in GitHub Desktop.
Save addityasingh/be82e4d1e9bbac528c0f002ecd9a026b to your computer and use it in GitHub Desktop.
jest.spyOn
import {foo, bar} from '../foo-bar';
import * as abc from '../util'
import * as https from 'https'
describe("asdf", () => {
test("foo", async () => {
jest.spyOn(https, 'request').mockImplementation(() => jest.fn() as any);
await foo('https://example.org');
expect(https.request).toHaveBeenCalledWith('https://example.org');
})
test("bar", () => {
jest.spyOn(abc, 'add').mockImplementation(() => 1234);
expect(bar()).toBe(1234)
expect(abc.add).toHaveBeenCalledWith(1, 2);
})
})
import {request as httpsRequest} from 'https';
import { Socket } from 'net';
import { add } from './util';
export const foo = async (url: string = "https://example.org") => {
return new Promise((resolve, reject) => {
const request = httpsRequest(url);
request.once('socket', (socket: Socket) => {
if(socket.connecting) {
socket.once('lookup', () => { console.log(process.hrtime())});
}
});
request.on("response", (response) => {
let chunks: Buffer[] = [];
let bufferLength = 0;
response.on("error", reject);
response.on("data", (data: any) => {
bufferLength += data.length;
chunks.push(data as Buffer);
});
response.on("end", () => {
response.body = Buffer.concat(chunks, bufferLength).toString("utf8");
chunks = [];
bufferLength = 0;
if (response.statusCode == null) {
response.statusCode = 0;
}
resolve(response);
});
});
request.on("error", (err: Error) => {
reject(new Error(err.message));
});
request.end();
})
};
export const bar = () => {
return add(1, 2);
}

Unable to make the spyOn method to make the spying work for https.request() method

Reproduce

  • Run the tests in foo-bar.ts
  • The test for bar works, when spying on add method from util.ts
  • The test for foo doesn't work, when spying on request method from https
export const add = (a: number, b: number) => a + b;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment