
Security News
RubyGems Adds Cooldown Feature to Bundler for Newly Published Gems
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.
A minimal, zero-dependency stub utility for JavaScript testing. Simple API, predictable behavior, and no magic—perfect for replacing Sinon in modern test setups.
A minimal, zero-dependency stub utility for JavaScript testing. With a simple yet powerful API and predictable behavior, it's the perfect replacement for Sinon in modern test setups. Its functional, declarative style makes test code more readable and maintainable.
import {stub} from 'stubfn';
const apiStub = stub()
.returns('success') // default return value
.when(['POST', '/users'], {id: 1, name: 'John'})
.when(['DELETE', '/users'], new Error('not allowed'));
console.log(apiStub('GET', '/users')); // 'success' (default return value)
console.log(apiStub('POST', '/users')); // {id: 1, name: 'John'}
console.log(apiStub('DELETE', '/users')); // Throws: Error: not allowed
console.log(apiStub.getCalls()); // [['GET', '/users'], ['POST', '/users'], ['DELETE', '/users']]
console.log(apiStub.getNumCalls()); // 3
npm i stubfn -D
stub(name?: string): StubCreates a function stub for use in unit tests. Accepts an optional name for better debugging, as the name will be included in the error message if the stub is called with unexpected arguments.
The returned stub function can be called like a normal function and includes additional methods.
See stub.ts for the full type definition.
Stub.reset(): StubResets the stub to its initial state. Clears recorded calls and resets internal expectations and return values.
Stub.clearCalls(): StubClears recorded calls. Does not reset internal expectations and return values.
Stub.getCalls(): any[]Returns an array of all calls made to the stub (each call is an array of arguments).
Stub.getNumCalls(): numberReturns the total number of times the stub has been called.
Stub.expects(...args: any[]): StubDefines the exact arguments the stub expects to receive. If the stub is called with different arguments, it throws an error. Uses deep equality comparison (by value, not reference). Cannot be used after when().
Stub.returns(value: any): StubSets the value that the stub should return when called. If the value is a function, it will be called with the stub's arguments. If no return value is set, the stub will return undefined.
If when() is used and the stub is called with arguments that match the when() arguments, the when() return value will be returned instead of the returns() value.
Stub.throws(error: Error): StubAn alias for returns(new Error(error)).
Stub.when(args: any[], returns: any): StubSets up a return value for a specific set of arguments. Cannot be used after expects(). Can be chained multiple times.
const myStub = stub();
myStub('hello'); // undefined
console.log(myStub.getCalls()); // [['hello']]
console.log(myStub.getNumCalls()); // 1
const myStub = stub()
.expects('hello', 123)
.returns('world');
console.log(myStub('hello', 123)); // 'world'
console.log(myStub.getCalls()); // [['hello', 123]]
console.log(myStub.getNumCalls()); // 1
myStub('potato'); // Throws: Stub called with unexpected arguments.
// Expected: ['hello', 123]
// Received: ['potato']
const serverStub = stub()
.throws(new Error('how rude')) // default
.when(['please'], "here you go")
.when(['thank you'], "you're welcome");
serverStub('please'); // 'here you go'
serverStub('thank you'); // 'you're welcome'
serverStub('gimme some grub'); // Throws: Error: how rude
Here's the domain code that we'll be testing. It's a simple function that checks if a user has completed their profile.
// hasCompletedProfile.ts
import {getUser} from './services/getUser';
export async function hasCompletedProfile(userId: string) {
const user = await getUser(userId);
return user.name && user.email && user.phone;
}
// hasCompletedProfile.spec.ts
import {test} from 'hoare';
import {mock, stub} from 'cjs-mock'; // for CJS modules only
// cjs-mock includes stubfn
import * as m from './hasCompletedProfile'; // get module type
const getUserStub = stub()
.when(['user123'], {
name: 'John',
email: 'john@example.com',
phone: '123-456-7890'
})
.when(['user456'], {
name: 'Jane',
email: 'jane@example.com',
phone: undefined // missing phone
});
// Require the module and mock out the dependencies
const mod: typeof m = mock('./hasCompletedProfile', {
'./services/getUser': {getUser: getUserStub}
});
test('hasCompletedProfile returns true if all fields are filled', async (assert) => {
// Test with different users
assert.isTrue(await sut.hasCompletedProfile('user123'));
assert.isFalse(await sut.hasCompletedProfile('user456'));
// Verify the stub was called with correct arguments
assert.equal(getUserStub.getCalls(), [['user123'], ['user456']]);
});
const errorStub = stub()
.throws(new Error('Network error'));
try {
await errorStub();
} catch (error) {
assert.equal(error.message, 'Network error');
}
const callbackStub = stub()
.returns((data: any) => data.toUpperCase());
const result = callbackStub()('hello');
assert.equal(result, 'HELLO');
If you find yourself needing more powerful features, or re-implementing dependencies, it might be a sign that your tests are too complex. Consider breaking your code into smaller, more testable units instead of adding complexity to your test setup.
However, if you want to add a feature, you can submit an issue or a PR. Contributions are welcome!
main and request review. Make sure all tests pass and coverage is good.Want to sponsor this project? Reach out.
FAQs
A minimal, zero-dependency stub utility for JavaScript testing. Simple API, predictable behavior, and no magic—perfect for replacing Sinon in modern test setups.
We found that stubfn demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.

Security News
pnpm 11.5 now recognizes npm staged publish approvals in release metadata, preventing those releases from being mistaken for lower-trust package publishes.

Security News
Federal audit finds NIST lacked a plan to clear the NVD backlog, wasted funds on duplicate work, and delayed use of CISA data.