How to use the match function from sinon
Find comprehensive JavaScript sinon.match code examples handpicked from public code repositorys.
sinon.match is a utility function in the Sinon.js library that allows for advanced argument matching in test assertions.
385 386 387 388 389 390 391 392 393 394
ref: '03e9577bc1ec60f2ff0929d5f1554de36b8f48cf', content: require('./data/yml/valid-yaml.json'), }); await simulateJobMessage({ user: 'TaskclusterRobot' }); assert(handlers.createTasks.calledWith({ scopes: sinon.match.array, tasks: sinon.match.array })); let args = handlers.createTasks.firstCall.args[0]; let taskGroupId = args.tasks[0].task.taskGroupId; let [build] = await helper.db.fns.get_github_build(taskGroupId); assert.equal(build.organization, 'TaskclusterRobot');
+ 23 other calls in file
GitHub: mozilla/fxa
379 380 381 382 383 384 385 386 387 388
email: 'joe@example.com', name: 'Joe Cool', description: uid, metadata: { userid: uid, geoip_date: sinon.match.any, }, shipping: { name: sinon.match.any, address: {
+ 2 other calls in file
How does sinon.match work?
sinon.match provides a way to perform advanced matching on arguments passed to a mocked or spied function in a test assertion. It allows the user to create a matcher object that can be used to compare the actual arguments passed to the function with the expected values or patterns. The matcher object can be created using various built-in matchers provided by Sinon.js, such as sinon.match.any, sinon.match.number, sinon.match.string, sinon.match.object, etc., or by creating a custom matcher function. When a mocked or spied function is called with arguments, the sinon.match utility compares each argument with the corresponding matcher in the expected argument list. If all the matchers match the actual arguments, the assertion passes; otherwise, it fails with an error message that indicates which matchers failed to match. This allows for more fine-grained control over test assertions, especially when dealing with complex or dynamic arguments, and can make test code more readable and maintainable.
168 169 170 171 172 173 174 175 176 177
t.context.fetchRulesStub.callsFake((params) => { t.deepEqual(params, { queryParams: { 'rule.type': 'sqs', state: 'ENABLED' } }); return rules.filter((rule) => rule.state === 'ENABLED'); }); const queueMessageFromEnabledRuleStub = queueMessageStub .withArgs(rules[1], sinon.match.any, sinon.match.any); // send two messages to the queue of the ENABLED sqs rule await Promise.all( range(2).map(() =>
+ 2 other calls in file
GitHub: nasa/cumulus
466 467 468 469 470 471 472 473 474 475 476 477
t.true(pMapSpy.calledOnce); t.true(pMapSpy.calledWithMatch( sinon.match.any, sinon.match.any, sinon.match({ concurrency: 17 }) )); }); test.serial('discover granules sets the GRANULES environment variable and logs the granules', async (t) => {
+ 17 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10
const sinon = require("sinon"); // Create a mocked function with a single argument const myFunc = sinon.stub(); // Call the mocked function with an argument myFunc("Hello, world!"); // Assert that the mocked function was called with the expected argument sinon.assert.calledWith(myFunc, sinon.match.string);
In this example, sinon.match.string is used as a matcher to check if the argument passed to myFunc is a string. If the assertion fails, the error message will indicate that the actual argument passed was not a string. Note that sinon.match can also be used to match against complex objects or data structures, regular expressions, or custom functions that perform more complex matching logic.
24 25 26 27 28 29 30 31 32
const requestURL = `Workspaces/${credentials.multiTaskWorkspaceSid}/Workers/${credentials.multiTaskAliceSid}`; const requestParams = { ActivitySid: credentials.multiTaskConnectActivitySid }; sandbox = sinon.sandbox.create(); const failedResponse = { response: { status: 429, statusText: 'failed on purpose' } } ; const requestStub = sandbox.stub(Request.prototype, 'post').withArgs(requestURL, requestParams, API_V1, sinon.match.any); // mocking the activity update request and making it fail, so retires are executed requestStub.rejects(failedResponse); message = /Retrying Update Worker Activity after backoff time: (\d+)ms for retryCount: (\d+)/;
+ 5 other calls in file
149 150 151 152 153 154 155 156 157 158
const indicesDefinition = dataContractJs.getDocumentSchema(williamType).indices; stateRepositoryMock.fetchDocuments .withArgs( sinon.match.instanceOf(Identifier), williamType, { where: [ ['$ownerId', '==', ownerId.toJSON()],
+ 13 other calls in file
233 234 235 236 237 238 239 240 241 242
.then(() => { should(websocket.retrying).be.true(); should(cb).be.calledTwice(); should(websocket.connect).be.calledOnce(); should(window.addEventListener).calledWith("online", sinon.match.func, { once: true, }); return clock.tickAsync(100);
101 102 103 104 105 106 107 108 109
req.account.connectorGatewayAccountStripeProgress = undefined await controller(req, res, next) sinon.assert.notCalled(res.redirect) const expectedError = sinon.match.instanceOf(Error) .and(sinon.match.has('message', 'Stripe setup progress is not available on request')) sinon.assert.calledWith(next, expectedError) })
+ 2 other calls in file
188 189 190 191 192 193 194 195 196 197
context("calling the updateJourneyState", () => { it("should raise an error when debug is set to false", async () => { req.session.isDebugJourney = false; await middleware.updateJourneyState(req, res, next); expect(next).to.have.been.calledWith( sinon.match.has("message", "Debug operation not available") ); }); it("should raise an error when given an invalid action", async () => {
+ 19 other calls in file
292 293 294 295 296 297 298 299 300 301
}) return it('should return a NotFoundError', function () { return this.callback .calledWith( sinon.match.has( 'message', `No such doc: ${this.doc_id} in project ${this.project_id}` ) )
+ 13 other calls in file
365 366 367 368 369 370 371 372 373
it('should import an identity from a path', async () => { await identityManagerFactory.create(stubWalletFacadeFactory, [org1MSPWithCertificates, org2MSPWithCertificates]); sinon.assert.calledTwice(stubInMemoryAndFileSystemWalletFacade.import); sinon.assert.calledWith(stubInMemoryAndFileSystemWalletFacade.import, 'Org1MSP', 'User1', sinon.match(/^-----BEGIN CERTIFICATE-----.*/), sinon.match(/^-----BEGIN PRIVATE KEY-----.*/)); sinon.assert.calledWith(stubInMemoryAndFileSystemWalletFacade.import, 'Org2MSP', '_Org2MSP_User1', sinon.match(/^-----BEGIN CERTIFICATE-----.*/), sinon.match(/^-----BEGIN PRIVATE KEY-----.*/)); });
+ 13 other calls in file
153 154 155 156 157 158 159 160 161 162
prometheusPushTxObserver._sendUpdate(); sinon.assert.calledWith(prometheusPushTxObserver.prometheusPushGateway.pushAdd, sinon.match({ jobName: 'caliper-workers', groupings: sinon.match({ workerIndex: 0, roundIndex: 2 }) }), sinon.match.func);
+ 3 other calls in file
244 245 246 247 248 249 250 251 252
const client = await session.client; sinon.assert.match(client, { ...baseClient, getInstance: sinon.match.func }); sinon.assert.calledWithExactly(ClientModel.prototype.getBy, 'code', 'some-client-code', { limit: 1 });
+ 9 other calls in file
812 813 814 815 816 817 818 819 820
) }) it('should return an error', function () { this.callback.should.have.been.calledWith( sinon.match.instanceOf(Errors.DocVersionDecrementedError) ) }) })
+ 79 other calls in file
sinon.stub is the most popular function in sinon (5777 examples)