Replace all instances of a specific import via jscodeshift - javascript

okay so I have code that looks like this:
import { wait } from "#testing-library/react";
describe("MyTest", () => {
it("should wait", async () => {
await wait(() => {
console.log("Done");
});
});
});
I want to change that import member wait to be waitFor. I'm able to change it in the AST like so:
source
.find(j.ImportDeclaration)
.filter((path) => path.node.source.value === "#testing-library/react")
.find(j.ImportSpecifier)
.filter((path) => path.node.imported.name === "wait")
.replaceWith(j.importSpecifier(j.identifier("waitFor")))
.toSource()
However, the outputed code will look as follows:
import { waitFor } from "#testing-library/react";
describe("MyTest", () => {
it("should wait", async () => {
await wait(() => {
console.log("Done");
});
});
});
I'm looking for a way to change all subsequent usages of that import to match the new name
Is this possible with jscodeshift?

You can do it by visiting all the CallExpression nodes, filtering for those with the name you're targeting ("wait") and replacing them with new nodes.
To find the relevant nodes you can either loop through the collection returned by jscodeshift's find() method and add your logic there, or you can give find() a second argument. This should be a predicate used for filtering:
const isWaitExpression = (node) =>
node.callee && node.callee.name === "wait";
// I've used "root" where you used "source"
root
.find(j.CallExpression, isWaitExpression)
Then you can replace those nodes with replaceWith():
const replaceExpression = (path, j) =>
j.callExpression(j.identifier("waitFor"), path.node.arguments);
root
.find(j.CallExpression, isWaitExpression)
.replaceWith((path) => replaceExpression(path, j));
It can look a bit confusing, but to create a CallExpression node, you call the callExpression() method from the api. Note the camel-casing there.
All together, a transformer that renames "wait" from RTL to "waitFor" — both the named import declaration and every instance where it's called in the file — can be done like this:
const isWaitExpression = (node) => node.callee && node.callee.name === "wait";
const replaceExpression = (path, j) =>
j.callExpression(j.identifier("waitFor"), path.node.arguments);
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
root
.find(j.ImportDeclaration)
.filter((path) => path.node.source.value === "#testing-library/react")
.find(j.ImportSpecifier)
.filter((path) => path.node.imported.name === "wait")
.replaceWith(j.importSpecifier(j.identifier("waitFor")));
root
.find(j.CallExpression, isWaitExpression)
.replaceWith((path) => replaceExpression(path, j));
return root.toSource();
}
And here's a link to it on AST explorer

Related

Jest - module exports / deconstructing causing requireActual to not work or not being able to intercept original method for mocking?

I've got a controller that calls two functions and in one test I would like to see if the child function is called and in my second test see if it returns the correct number.
// ./utilities/sayMyName.js
exports.sayMyName = (name) => name;
// ./utilities/doubleNum.js
exports.doubleNum = (num) => num * 2;
// ./utilities/index.js
const { doubleNum } = require("./doubleNum");
const { sayMyName } = require("./sayMyName");
module.exports = {
doubleNum,
sayMyName,
};
// myController.js
const { doubleNum, sayMyName } = require("./utilities");
exports.doubleMyNum = (num, name) => {
const myName = sayMyName(name);
return doubleNum(num);
};
// myController.test.js
const myController = require("./myController");
const utilities = require("./utilities");
jest.mock("./utilities");
describe("doubleNum", () => {
test("should call sayMyName", () => {
myController.doubleMyNum(2, "test name");
expect(utilities.sayMyName).toHaveBeenCalledWith("test name");
});
test("should double my number", () => {
const { doubleNum } = jest.requireActual("./utilities");
expect(myController.doubleMyNum(2, "test name")).toBe(4);
});
});
First test passes however it's the second one that fails because I originally mocked the utilities module, I followed the docs and using jest.requireActual should bring back the original function but it isn't. I did read that mapping the exports like I did in index.js and using deconstructing can cause issues with intercepting a function to mock it. How can I go about getting this to work?
SORTED
After much reading and testing I'd like to think I've sorted the issue by realising that I was trying to change the implementation of function from index.js that was already imported into the myController.js file that contained the function I was testing
So for example if I want to change the implementation of only one of the exported functions from my index.js file I need to mock the module and reimport myController.js for it to have an affect. So this works:
const myController = require("./myController");
const utilities = require("./utilities");
jest.mock("./utilities");
describe("doubleNum", () => {
beforeEach(() => {
jest.resetModules();
});
test("should call sayMyName", () => {
const spy = jest.spyOn(utilities, "sayMyName");
myController.doubleMyNum(2, "test name");
expect(spy).toHaveBeenCalledWith("test name");
});
test("should double my number", () => {
jest.mock("./utilities", () => {
const { sayMyName, doubleNum } = jest.requireActual("./utilities");
return {
sayMyName,
doubleNum,
};
});
// Reimport myController for the actual utilities module to be restored
const myController = require("./myController");
expect(myController.doubleMyNum(2, "test name")).toBe(4);
});
});
Of course this could be simplified had I not used deconstruction in myController.js, hopefully someone else finds this helpful.
I think this might be because you aren’t doing the mocking in a beforeEach or beforeAll block.
Alternatively, you can look at the resetModules example here, and mock or require the module within each test block instead of for all tests: jest.resetModules

How to stub a "wrapper" function using Sinon?

I'm setting up a Lambda function (node.js) and for example's sake, we'll keep it minimal.
module.exports = (event, context, callback) {
console.log("hello world")
}
However, I've created a function to wrap the lambda function that allows me to perform some functions that are required before each Lambda executes (I have a collection of Lambda functions that are wired up using their Serverless Application Model (SAM)). It also allows me to consolidate some of the logging and error handling across each function.
// hook.js
const connect = fn => (event, context, callback) => {
someFunction()
.then(() => fn(event, context, callback))
.then(res => callback(null, res))
.catch(error => {
// logging
callback(error)
})
}
module.exports = { connect }
// index.js
const Hook = require("./hook")
exports.handler = Hook.connect((event, context, callback) => {
console.log("hello world")
})
The logic is working well and Lambda is processing it successfully. However, I'm trying to stub this Hook.connect function using SinonJS and in need of some guidance.
I simply want to stub it to return a resolved promise, that way we can proceed to handle the code within each Lambda function (fn(event, context, callback)).
const sinon = require("sinon")
const Hook = require("./hook")
const { handler } = require("./index")
const event = {} // for simplicity sake
const context = {} // for simplicity sake
const callback = {} // for simplicity sake
describe("Hello", () => {
let connectStub
beforeEach(() => {
connectStub = sinon.stub(Hook, "connect").callsFake()
afterEach(() => {
connectStub.restore()
})
it("works", () => {
const results = handler(event, context, callback)
// assert
})
})
I've tried a few different methods, from the basic, sinon.stub(Hook, "connect"), to the more complicated where I'm trying to stub private functions inside of the hook.js file using rewire.
Any help would be appreciated -- thank you in advance.
Here is a working test:
const sinon = require('sinon');
const Hook = require('./hook');
const event = {}; // for simplicity sake
const context = {}; // for simplicity sake
const callback = {}; // for simplicity sake
describe('Hello', () => {
let handler, connectStub;
before(() => {
connectStub = sinon.stub(Hook, 'connect');
connectStub.callsFake(fn => (...args) => fn(...args)); // create the mock...
delete require.cache[require.resolve('./index')]; // (in case it's already cached)
handler = require('./index').handler; // <= ...now require index.js
});
after(() => {
connectStub.restore(); // restore Hook.connect
delete require.cache[require.resolve('./index')]; // remove the modified index.js
});
it('works', () => {
const results = handler(event, context, callback); // it works!
// assert
});
});
Details
index.js calls Hook.connect to create its exported handler as soon as it runs, and it runs as soon as it is required...
...so the mock for Hook.connect needs to be in place before index.js is required:
Node.js caches modules, so this test also clears the Node.js cache before and after the test to ensure that index.js picks up the Hook.connect mock, and to ensure that the index.js with the mocked Hook.connect is removed from the cache in case the real index.js is needed later.

How To Reset Manual Mocks In Jest

I have a manual mock of crypto that looks like this:
// __mocks__/crypto.js
const crypto = jest.genMockFromModule('crypto')
const toString: Function = jest.fn(() => {
return {}.toString()
})
const mockStringable = {toString}
const update: Function = jest.fn(() => mockStringable)
const deciper = {update}
crypto.createDecipheriv = jest.fn(() => deciper)
export default crypto
Which is basically tested like this:
const crypto = require('crypto')
jest.mock('crypto')
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('decryptCookieValue', () => {
it('should call the crypto library correctly', () => {
const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
expect(crypto.createDecipheriv).toHaveBeenCalled()
// more tests, etc, etc, etc
expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
expect(result).toEqual({}.toString())
})
})
...
This works however if in that same test file, I test another method that invokes decryptCookieValue from within crypto.createDecipheriv no longer returns my mock decipher. Instead it returns undefined. For instance:
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('decryptCookieValue', () => {
it('should call the crypto library correctly', () => {
const result = decryptCookieValue('test-encryption-key', 'test-encrypted-value')
expect(crypto.pbkdf2Sync).toHaveBeenCalledTimes(2)
expect(crypto.createDecipheriv).toHaveBeenCalled()
expect(crypto.createDecipheriv('', '', '').update).toHaveBeenCalled()
expect(result).toEqual({}.toString())
})
})
...
...
describe('parseAuthenticationCookie', () => {
it('should create the correct object', () => {
// parseAuthenticationCookie calls decryptCookieValue internally
const result = parseAuthenticationCookie('', '') // Fails because internal call to crypto.createDecipheriv stops returning mock decipher.
expect(result).toEqual({accessToken: null})
})
})
})
I think this is an issue with resetting the manual mock because if I take that later test and move it into a file all by itself with the same surrounding test harness it works just fine.
// new test file
import crypto from 'crypto'
import { parseAuthenticationCookie } from './index'
jest.mock('crypto')
describe('cookie-parser', () => {
afterEach(() => {
jest.resetAllMocks()
})
describe('parseAuthenticationCookie', () => {
it('should create the correct object', () => {
// Works just fine now
const result = parseAuthenticationCookie('', '')
expect(result).toEqual({accessToken: null})
})
})
})
Is my assessment here correct and, if so, how do I reset the state of the manual mock after each test?
From Jest docs:
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
ref: https://jestjs.io/docs/en/mock-function-api#mockfnmockreset
In your example you are assuming that calling resetAllMocks will set your manual mock back and it's not.
The reason why your test works in a separate file is because jest runs each file isolated, which is nice since you can screw up only the specs living in the same file.
In your particular case something that might work is calling jest.clearAllMocks() (since this will keep the implementation and returned values).
clearMocks options is also available at the jest config object (false as default), if you want to clear all your mocks on every test, this might be handy.
Hope this help you or anyone else having having a similar issue.
Bonus tip (no quite related) If you are mocking a module that it's being used internally by other module and in some specific test you want to mock that module again with a different mock, make sure to require the module that it's using the mocked module internally again in that specific test, otherwise that module will still reference the mock you specified next to the imports statements.
Looks like the better way to test this is something on the lines of:
jest.mock('crypto')
describe('decrypt()', () => {
afterEach(() => {
jest.resetAllMocks()
})
it('returns value', () => {
const crypto = require('crypto')
const encryptedValue = 'encrypted-value'
const update = jest.fn()
const pbkdf2SyncResult = 'test result'
crypto.pbkdf2Sync = jest.fn().mockImplementation(() => {
return pbkdf2SyncResult
})
crypto.createDecipheriv = jest.fn().mockImplementation((format, key, iv) => {
expect(format).toEqual('aes-256-cbc')
expect(key).toEqual(pbkdf2SyncResult)
expect(iv).toEqual(pbkdf2SyncResult)
return {update}
})
decrypt(encryptedValue)
const inputBuffer = Buffer.from(encryptedValue, 'base64')
expect(update).toHaveBeenCalledWith(inputBuffer)
})
})
This way I don't even have to have the manual mock and I can use mockImplementationOnce if I need to have the mock reset.

How to change mock implementation on a per single test basis?

I'd like to change the implementation of a mocked dependency on a per single test basis by extending the default mock's behaviour and reverting it back to the original implementation when the next test executes.
More briefly, this is what I'm trying to achieve:
Mock dependency
Change/extend mock implementation in a single test
Revert back to original mock when next test executes
I'm currently using Jest v21. Here is what a typical test would look like:
// __mocks__/myModule.js
const myMockedModule = jest.genMockFromModule('../myModule');
myMockedModule.a = jest.fn(() => true);
myMockedModule.b = jest.fn(() => true);
export default myMockedModule;
// __tests__/myTest.js
import myMockedModule from '../myModule';
// Mock myModule
jest.mock('../myModule');
beforeEach(() => {
jest.clearAllMocks();
});
describe('MyTest', () => {
it('should test with default mock', () => {
myMockedModule.a(); // === true
myMockedModule.b(); // === true
});
it('should override myMockedModule.b mock result (and leave the other methods untouched)', () => {
// Extend change mock
myMockedModule.a(); // === true
myMockedModule.b(); // === 'overridden'
// Restore mock to original implementation with no side effects
});
it('should revert back to default myMockedModule mock', () => {
myMockedModule.a(); // === true
myMockedModule.b(); // === true
});
});
Here is what I've tried so far:
mockFn.mockImplementationOnce(fn)
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
myMockedModule.b.mockImplementationOnce(() => 'overridden');
myModule.a(); // === true
myModule.b(); // === 'overridden'
});
Pros
Reverts back to original implementation after first call
Cons
It breaks if the test calls b multiple times
It doesn't revert to original implementation until b is not called (leaking out in the next test)
jest.doMock(moduleName, factory, options)
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
jest.doMock('../myModule', () => {
return {
a: jest.fn(() => true,
b: jest.fn(() => 'overridden',
}
});
myModule.a(); // === true
myModule.b(); // === 'overridden'
});
Pros
Explicitly re-mocks on every test
Cons
Cannot define default mock implementation for all tests
Cannot extend default implementation forcing to re-declare each mocked method
Manual mocking with setter methods (as explained here)
// __mocks__/myModule.js
const myMockedModule = jest.genMockFromModule('../myModule');
let a = true;
let b = true;
myMockedModule.a = jest.fn(() => a);
myMockedModule.b = jest.fn(() => b);
myMockedModule.__setA = (value) => { a = value };
myMockedModule.__setB = (value) => { b = value };
myMockedModule.__reset = () => {
a = true;
b = true;
};
export default myMockedModule;
// __tests__/myTest.js
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
myModule.__setB('overridden');
myModule.a(); // === true
myModule.b(); // === 'overridden'
myModule.__reset();
});
Pros
Full control over mocked results
Cons
Lot of boilerplate code
Hard to maintain on long term
jest.spyOn(object, methodName)
beforeEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
// Mock myModule
jest.mock('../myModule');
it('should override myModule.b mock result (and leave the other methods untouched)', () => {
const spy = jest.spyOn(myMockedModule, 'b').mockImplementation(() => 'overridden');
myMockedModule.a(); // === true
myMockedModule.b(); // === 'overridden'
// How to get back to original mocked value?
});
Cons
I can't revert mockImplementation back to the original mocked return value, therefore affecting the next tests
Use mockFn.mockImplementation(fn).
import { funcToMock } from './somewhere';
jest.mock('./somewhere');
beforeEach(() => {
funcToMock.mockImplementation(() => { /* default implementation */ });
// (funcToMock as jest.Mock)... in TS
});
test('case that needs a different implementation of funcToMock', () => {
funcToMock.mockImplementation(() => { /* implementation specific to this test */ });
// (funcToMock as jest.Mock)... in TS
// ...
});
A nice pattern for writing tests is to create a setup factory function that returns the data you need for testing the current module.
Below is some sample code following your second example although allows the provision of default and override values in a reusable way.
const spyReturns = returnValue => jest.fn(() => returnValue);
describe("scenario", () => {
beforeEach(() => {
jest.resetModules();
});
const setup = (mockOverrides) => {
const mockedFunctions = {
a: spyReturns(true),
b: spyReturns(true),
...mockOverrides
}
jest.doMock('../myModule', () => mockedFunctions)
return {
mockedModule: require('../myModule')
}
}
it("should return true for module a", () => {
const { mockedModule } = setup();
expect(mockedModule.a()).toEqual(true)
});
it("should return override for module a", () => {
const EXPECTED_VALUE = "override"
const { mockedModule } = setup({ a: spyReturns(EXPECTED_VALUE)});
expect(mockedModule.a()).toEqual(EXPECTED_VALUE)
});
});
It's important to say that you must reset modules that have been cached using jest.resetModules(). This can be done in beforeEach or a similar teardown function.
See jest object documentation for more info: https://jestjs.io/docs/jest-object.
Little late to the party, but if someone else is having issues with this.
We use TypeScript, ES6 and babel for react-native development.
We usually mock external NPM modules in the root __mocks__ directory.
I wanted to override a specific function of a module in the Auth class of aws-amplify for a specific test.
import { Auth } from 'aws-amplify';
import GetJwtToken from './GetJwtToken';
...
it('When idToken should return "123"', async () => {
const spy = jest.spyOn(Auth, 'currentSession').mockImplementation(() => ({
getIdToken: () => ({
getJwtToken: () => '123',
}),
}));
const result = await GetJwtToken();
expect(result).toBe('123');
spy.mockRestore();
});
Gist:
https://gist.github.com/thomashagstrom/e5bffe6c3e3acec592201b6892226af2
Tutorial:
https://medium.com/p/b4ac52a005d#19c5
When mocking a single method (when it's required to leave the rest of a class/module implementation intact) I discovered the following approach to be helpful to reset any implementation tweaks from individual tests.
I found this approach to be the concisest one, with no need to jest.mock something at the beginning of the file etc. You need just the code you see below to mock MyClass.methodName. Another advantage is that by default spyOn keeps the original method implementation but also saves all the stats (# of calls, arguments, results etc.) to test against, and keeping the default implementation is a must in some cases. So you have the flexibility to keep the default implementation or to change it with a simple addition of .mockImplementation as mentioned in the code below.
The code is in Typescript with comments highlighting the difference for JS (the difference is in one line, to be precise). Tested with Jest 26.6.
describe('test set', () => {
let mockedFn: jest.SpyInstance<void>; // void is the return value of the mocked function, change as necessary
// For plain JS use just: let mockedFn;
beforeEach(() => {
mockedFn = jest.spyOn(MyClass.prototype, 'methodName');
// Use the following instead if you need not to just spy but also to replace the default method implementation:
// mockedFn = jest.spyOn(MyClass.prototype, 'methodName').mockImplementation(() => {/*custom implementation*/});
});
afterEach(() => {
// Reset to the original method implementation (non-mocked) and clear all the mock data
mockedFn.mockRestore();
});
it('does first thing', () => {
/* Test with the default mock implementation */
});
it('does second thing', () => {
mockedFn.mockImplementation(() => {/*custom implementation just for this test*/});
/* Test utilising this custom mock implementation. It is reset after the test. */
});
it('does third thing', () => {
/* Another test with the default mock implementation */
});
});
I did not manage to define the mock inside the test itself so I discover that I could mock several results for the same service mock like this :
jest.mock("#/services/ApiService", () => {
return {
apiService: {
get: jest.fn()
.mockResolvedValueOnce({response: {value:"Value", label:"Test"}})
.mockResolvedValueOnce(null),
}
};
});
I hope it'll help someone :)
It's a very cool way I've discovered on this blog https://mikeborozdin.com/post/changing-jest-mocks-between-tests/
import { sayHello } from './say-hello';
import * as config from './config';
jest.mock('./config', () => ({
__esModule: true,
CAPITALIZE: null
}));
describe('say-hello', () => {
test('Capitalizes name if config requires that', () => {
config.CAPITALIZE = true;
expect(sayHello('john')).toBe('Hi, John');
});
test('does not capitalize name if config does not require that', () => {
config.CAPITALIZE = false;
expect(sayHello('john')).toBe('Hi, john');
});
});

Jest basics: Testing function from component

I have a basic function:
components/FirstComponent:
sayMyName = (fruit) => {
alert("Hello, I'm " + fruit);
return fruit;
}
When I try to test it with Jest inside FirstComponent.test.js:
import FirstComponent from '../components/FirstComponent';
describe('<FirstComponent />', () => {
it('tests the only function', () => {
FirstComponent.sayMyName = jest.fn();
const value = FirstComponent.sayMyName('orange');
expect(value).toBe('orange');
});
});
Test says: Comparing two different types of values. Expected string but received undefined.
Apparently I'm not importing the function to test the right way?
I was not smart enough to understand the Jest documents how to test functions from components..
Is there some simple way to import function from component and test it?
Edit:
This works now using the 'react-test-renderer'
import FirstComponent from '../components/FirstComponent';
import renderer from 'react-test-renderer';
describe('<FirstComponent /> functions', () => {
it('test the only function', () => {
const wrapper = renderer.create(<FirstComponent />);
const inst = wrapper.getInstance();
expect(inst.sayMyName('orange')).toMatchSnapshot();
});
})
You have stubbed the function with one that does not return anything. FirstComponent.sayMyName = jest.fn();
To test the function, typically you can just do
// if static etc
import { sayMyName } from '../foo/bar';
describe('bar', () => {
it('should do what I like', () => {
expect(sayMyName('orange')).toMatchSnapshot();
});
})
This will store the output ("orange") and assert that every time you run this test, it should return orange. If your function stops doing that or returns something else, snapshot will differ and test will fail.
the direct comparison .toBe('orange') will still be possible but the really useful thing about jest is snapshot testing so you don't need to duplicate logic and serialise/deep compare structures or jsx.
if it's a component method, you need to render it first, getInstance() and then call it.

Categories

Resources