Skip to content

Instantly share code, notes, and snippets.

@gdekefir
Created April 14, 2017 20:24
Show Gist options
  • Save gdekefir/49facf4eeec1e2a5352ff4fa6bbf7286 to your computer and use it in GitHub Desktop.
Save gdekefir/49facf4eeec1e2a5352ff4fa6bbf7286 to your computer and use it in GitHub Desktop.
Mocking Observable.ajax.get
jest.mock('./process-env');
import Mock = jest.Mock;
import {Observable} from 'rxjs';
import {get} from './requests';
import {getProcessEnv} from './process-env';
describe('get', () => {
const originalAjaxGet = Observable.ajax.get;
const API_KEY = 'some';
beforeEach(() => {
// because "get" method uses "API_KEY", that returned by "getProcessEnv" method
(getProcessEnv as Mock<any>).mockImplementationOnce(() => ({
API_KEY
}));
});
afterEach(() => {
Observable.ajax.get = originalAjaxGet;
});
it('Observable.ajax.get is called once', () => {
Observable.ajax.get = jest.fn(() => Observable.of(null));
get('http://some-url.com');
const calls = (Observable.ajax.get as Mock<any>).mock.calls;
expect(Array.isArray(calls)).toBeTruthy();
expect(calls.length).toEqual(1);
});
it('Observable.ajax.get is called with 1-st arg which equals to a passed URL', () => {
Observable.ajax.get = jest.fn(() => Observable.of(null));
get('http://some-url.com');
const firstCall = (Observable.ajax.get as Mock<any>).mock.calls[0];
const firstArg = firstCall[0];
expect(firstArg).toEqual('http://some-url.com');
});
});
@HaveF
Copy link

HaveF commented Jul 18, 2021

Thanks.
Could it possible to mock get other than null?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment