I have a set of functions in a util module. Most of the functions are simple data manipulation, however, one of them makes a REST call. Many modules/classes call this method that makes the REST call for its values. Instead of the app/browser making multiple (>20) of the calls, can i make 1, and save the result. Then return the saved result and refrain from making subsequent calls?
utils.ts
import axios from 'axios'
import { of, from } from 'rxjs';
import { shareReplay, switchMap, first } from 'rxjs/operators';
let cache: Observable<any>; // <-- global cache to set/get
export function makeRequest() {
const promise = axios.get('http:rest-server:1234/user/data');
const obs = from(promise);
return obs.pipe(
map(res => { return of(res) })
catchError(err => { cache })
);
}
export function getUserData() {
if(!cache) { // <-- if cache isnt empty, make the REST call
cache = makeRequest()
.pipe(
shareReplay(2),
first()
)
}
return cache; // <- return the originally populated cache
}
index.ts
import * as Config from './utils';
myComponent.ts
import { Config } from 'my-helper-library';
export class MyComponent {
public init() {
Config.getUserData()
.subscribe(.......
}
}
Note, this singleton will be consumed by both Angular and React apps.
I have a quite simple test, basically I'm trying to mock i18next's t function:
import { t } from 'i18next';
import { changeDocumentTitle } from './utils';
jest.mock('i18next');
const tMock = (key: string): string => key;
beforeAll(() => {
(t as jest.Mock).mockImplementation(tMock);
});
test('test changeDocumentTitle function', () => {
changeDocumentTitle('string');
expect(document.title).toEqual(tMock('string'));
});
and the changeDocumentTitle implementation:
import { t } from 'i18next';
export const changeDocumentTitle = (titleKey: string): void => {
document.title = t(`${titleKey}`);
};
Unfortunately, the test fails. But if I change it from beforeAll to beforeEach, everything's fine. How is that? Why beforeAll is not applying my mock unlike beforeEach?
Thanks in advance.
Since react-scripts v4 it added the default jest config resetMocks: true: https://github.com/facebook/create-react-app/releases/tag/v4.0.0
This means that the mocks are being reset before the tests runs with beforeAll. I recommended keeping resetMocks: true, because tests should be isolated.
I have just changed my lodash import from import _ from 'lodash'; to import debounce from 'lodash/debounce';
In my test I used to have sandbox.stub(_, 'debounce').returnsArg(0);, but now I'm stuck as to what to change it to. Obviously sandbox.stub(debounce).returnsArg(0); won't work. Not sure what to do when only a single function is exported from a module.
This syntax:
import something from 'myModule';
...is ES6 syntax which binds something to the default export of 'myModule'.
If the module is an ES6 module then you can stub the default export of the module like this:
import * as myModule from 'myModule';
const sinon = require('sinon');
// ...
const stub = sinon.stub(myModule, 'default');
...but this only works if 'myModule' is an ES6 module.
In this case 'lodash/debounce' is not an ES6 module, it is shipped pre-compiled. The last line is this:
module.exports = debounce;
...which means the module export is the debounce function.
This means that in order to stub 'lodash/debounce' you have to mock the entire module.
Sinon doesn't provide module-level mocking so you will need to use something like proxyquire:
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const debounceStub = sinon.stub().returnsArg(0);
const code = proxyquire('[path to your code]', { 'lodash/debounce': debounceStub })
...or if you are using Jest you can use something like jest.mock:
jest.mock('lodash/debounce', () =>
jest.fn((func, ms) => func) // <= mock debounce to simply return the function
);
Details
The reason that stubbing the default export of a module only works if it is an ES6 module is because of what happens during compilation.
ES6 syntax gets compiled into pre-ES6 JavaScript. For example, Babel turns this:
import something from 'myModule';
...into this:
var _myModule = _interopRequireDefault(require("myModule"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ?
obj : // <= return the result of require("myModule") if it is an ES6 module...
{ default: obj }; // <= otherwise set it to the default property of a wrapper object
}
...so if 'myModule' is an ES6 module it gets returned directly...but if it is not then the interop returns a wrapping object.
Since each import gets a different wrapping object, changing the default property on one doesn't affect the default property of any others.
you can make yourself a wrapping file, which will eventually export the same lodash/debounce instance for you, but this time you could stub that, e.g.:
myutils/lodash/debounce.js
import lodashDebounce from 'lodash/debounce';
const exports = {
debounce: lodashDebounce,
};
export const debounce = () => exports.debounce();
export default exports;
now, in your actual code import the debounce not from the original location, but from this wrapping file instead:
BEFORE:
import debounce from 'lodash/debounce' // this is how we usually do
AFTER:
import { debounce } from 'myutils/lodash/debounce' // if we want to stub it
// all other code-lines remain the same
const method = () => {
debounce(callback, 150));
...
}
now when doing a test.js:
import lodashWrapped from 'myutils/lodash/debounce';
sinon.stub(lodashWrapped , 'debounce').callsFake((callbackFn) => {
// this is stubbed now
});
// go on, make your tests now
Now that we have "lettable" operators, how should we go about creating an Observable from another?
When I try to do:
import {Observable} from 'rxjs/Observable'
const source = Observable.from(someOtherStream)
I get the error Observable.from is not a function, which makes sense, because from is now something else that needs to be imported separately.
I don't want to do
import 'rxjs/add/observable/from' anymore due to the prototypal problems there.
What I ended up doing was:
import { Observable } from 'rxjs/Observable'
import { from } from 'rxjs/observable/from'
const myNewStream = from.call(
Observable,
someOtherStream
)
But this really feels "hacky" for some reason to me. Does anyone have any better ways of going about this?
The lettables are behind rxjs/operators here's the write up on it.
For from you should be able to import it without importing Observable.
import { from } from 'rxjs/observable/from';
const prom = new Promise(res => setTimeout(
() => res('promise'), 3000
));
from(prom).subscribe(x => console.log(x));
webpackbin example
Using from this way allows you to pipe() to the lettable operators.
import { from } from 'rxjs/observable/from';
import { map } from 'rxjs/operators/map';
const prom = new Promise(res => setTimeout(
() => res('promise'), 3000
));
from(prom).pipe(
map(x => x.split('').reverse().join(''))
).subscribe(x => console.log(x));
webpackbin example
I think this is misunderstanding what from does. It's just a function that takes a "stream" (that's Observable, Promise, array, ...) and creates an Observable from it.
This means you use it just like any other function:
import { from } from 'rxjs/observable/from'
from(someOtherStream).pipe(...).subscribe(...)
I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --
The application code:
// myModule.js
import dependency from './dependency';
export default (x) => {
dependency.doSomething(x * 2);
}
And the test code:
//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
spyOn(dependency, 'doSomething');
myModule(2);
expect(dependency.doSomething).toHaveBeenCalledWith(4);
});
});
What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.
The closest I've come is by replacing the imports with requires, and moving them inside the tests/functions. Neither of which are things I want to do.
// myModule.js
export default (x) => {
const dependency = require('./dependency'); // Yuck
dependency.doSomething(x * 2);
}
//myModule-test.js
describe('myModule', () => {
it('calls the dependency with double the input', () => {
jest.mock('../dependency');
myModule(2);
const dependency = require('../dependency'); // Also yuck
expect(dependency.doSomething).toBeCalledWith(4);
});
});
For bonus points, I'd love to make the whole thing work when the function inside dependency.js is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.
Edit: Several years have passed and this isn't really the right way to do this any more (and probably never was, my bad).
Mutating an imported module is nasty and can lead to side effects like tests that pass or fail depending on execution order.
I'm leaving this answer in its original form for historical purposes, but you should really use jest.spyOn or jest.mock. Refer to the jest docs or the other answers on this page for details.
Original answer follows:
I've been able to solve this by using a hack involving import *. It even works for both named and default exports!
For a named export:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.doSomething = jest.fn(); // Mutate the named export
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
Or for a default export:
// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.default = jest.fn(); // Mutate the default export
myModule(2);
expect(dependency.default).toBeCalledWith(4); // Assert against the default
});
});
You have to mock the module and set the spy by yourself:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
doSomething: jest.fn()
}))
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export
Using only ES6 module syntax:
// esModule.js
export default 'defaultExport';
export const namedExport = () => {};
// esModule.test.js
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function
Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.
To mock an ES6 dependency module default export using Jest:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);
describe('myModule', () => {
it('calls the dependency once with double the input', () => {
myModule(2);
expect(dependency).toHaveBeenCalledTimes(1);
expect(dependency).toHaveBeenCalledWith(4);
});
});
The other options didn't work for my case.
Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
});
});
And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.
The question is already answered, but you can resolve it like this:
File dependency.js
const doSomething = (x) => x
export default doSomething;
File myModule.js
import doSomething from "./dependency";
export default (x) => doSomething(x * 2);
File myModule.spec.js
jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";
describe('myModule', () => {
it('calls the dependency with double the input', () => {
doSomething.mockImplementation((x) => x * 10)
myModule(2);
expect(doSomething).toHaveBeenCalledWith(4);
console.log(myModule(2)) // 40
});
});
None of the answers here seemed to work for me (the original function was always being imported rather than the mock), and it seems that ESM support in Jest is still work in progress.
After discovering this comment, I found out that jest.mock() does not actually work with regular imports, because the imports are always run before the mock (this is now also officially documented). Because of this, I am importing my dependencies using await import(). This even works with a top-level await, so I just have to adapt my imports:
import { describe, expect, it, jest } from '#jest/globals';
jest.unstable_mockModule('../dependency', () => ({
doSomething: jest.fn()
}));
const myModule = await import('../myModule');
const dependency = await import('../dependency');
describe('myModule', async () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
I solved this another way. Let's say you have your dependency.js
export const myFunction = () => { }
I create a depdency.mock.js file besides it with the following content:
export const mockFunction = jest.fn();
jest.mock('dependency.js', () => ({ myFunction: mockFunction }));
And in the test, before I import the file that has the dependency, I use:
import { mockFunction } from 'dependency.mock'
import functionThatCallsDep from './tested-code'
it('my test', () => {
mockFunction.returnValue(false);
functionThatCallsDep();
expect(mockFunction).toHaveBeenCalled();
})
I tried all the solutions and none worked or were showing lots of TS errors.
This is how I solved it:
format.ts file:
import camelcaseKeys from 'camelcase-keys'
import parse from 'xml-parser'
class Format {
parseXml (xml: string) {
return camelcaseKeys(parse(xml), {
deep: true,
})
}
}
const format = new Format()
export { format }
format.test.ts file:
import format from './format'
import camelcaseKeys from 'camelcase-keys'
import parse from 'xml-parser'
jest.mock('xml-parser', () => jest.fn().mockReturnValue('parsed'))
jest.mock('camelcase-keys', () => jest.fn().mockReturnValue('camel cased'))
describe('parseXml', () => {
test('functions called', () => {
const result = format.parseXml('XML')
expect(parse).toHaveBeenCalledWith('XML')
expect(camelcaseKeys).toHaveBeenCalledWith('parsed', { deep: true })
expect(result).toBe('camel cased')
})
})
I made some modifications on #cam-jackson original answer and side effects has gone. I used lodash library to deep clone the object under test and then made any modification I want on that object. But be ware that cloning heavy objects can have negative impact on test performance and test speed.
objectUndertest.js
const objectUnderTest = {};
export default objectUnderTest;
objectUnderTest.myFunctionUnterTest = () => {
return "this is original function";
};
objectUndertest.test.js
import _ from "lodash";
import objectUndertest from "./objectUndertest.js";
describe("objectUndertest", () => {
let mockObject = objectUndertest;
beforeEach(() => {
mockObject = _.cloneDeep(objectUndertest);
});
test("test function", () => {
mockObject.myFunctionUnterTest = () => {
return "this is mocked function.";
};
expect(mockObject.myFunctionUnterTest()).toBe("this is mocked function.");
});
});