{"id":13452620,"url":"https://github.com/florinn/typemoq","last_synced_at":"2025-05-15T23:07:10.437Z","repository":{"id":24244978,"uuid":"27638171","full_name":"florinn/typemoq","owner":"florinn","description":"A simple mocking library for TypeScript","archived":false,"fork":false,"pushed_at":"2023-01-11T06:55:26.000Z","size":969,"stargazers_count":429,"open_issues_count":53,"forks_count":46,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-04-29T11:43:59.208Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/florinn.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-12-06T15:08:39.000Z","updated_at":"2025-02-27T16:33:12.000Z","dependencies_parsed_at":"2023-01-14T00:38:27.525Z","dependency_job_id":null,"html_url":"https://github.com/florinn/typemoq","commit_stats":null,"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinn%2Ftypemoq","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinn%2Ftypemoq/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinn%2Ftypemoq/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/florinn%2Ftypemoq/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/florinn","download_url":"https://codeload.github.com/florinn/typemoq/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253398098,"owners_count":21902036,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T07:01:29.418Z","updated_at":"2025-05-15T23:07:04.687Z","avatar_url":"https://github.com/florinn.png","language":"TypeScript","readme":"TypeMoq [![build badge](https://travis-ci.org/florinn/typemoq.svg?branch=master)](https://travis-ci.org/florinn/typemoq)\n===================\n\nSimple mocking library for JavaScript targeting [TypeScript](http://www.typescriptlang.org/) development. If you have used before a library like [Moq](https://github.com/Moq/moq4) then the syntax should look familiar, otherwise the examples below should hopefully provide enough information to get you started quickly.\n\n\nFeatures\n-------------\n* Strongly typed\n* Auto complete/intellisense support\n* Static and dynamic mocking\n* Mock objects, classes (with arguments), constructor functions and interfaces\n* Control mock behavior\n* Record and replay expectations\n* Auto sandbox global objects and types\n* Support ECMAScript 5 and 6\n* Support node.js and browser\n\n[![Sauce Test Status](https://saucelabs.com/browser-matrix/florinn.svg)](https://saucelabs.com/u/florinn)\n\n\nInstalling\n-------------\n\n###### Release version\n\n```\nnpm install typemoq\n```\n\nOr add this *NuGet* dependency to your project:\n```\nPM\u003e Install-Package typemoq \n```\n\nThe distribution directory should contain:\n\n* *Compiled JavaScript:* `typemoq.js` and its minified version `typemoq-min.js`\n* *TypeScript definitions:* `typemoq.d.ts`\n\n###### Development version\n\n```\nnpm install https://github.com/florinn/typemoq\n```\n\n\n##### Node.js\n\n###### TypeScript 1.6 and later\n\n```typescript\nimport * as TypeMoq from \"typemoq\";\n```\n\n###### TypeScript pre 1.6\n\n```typescript\n/// \u003creference path=\"./node_modules/typemoq/dist/typemoq.d.ts\" /\u003e\nTypeMoq = require(\"typemoq\");\n```\n\n\n##### Browser\n\nInclude at the top of your script file:\n```typescript\n/// \u003creference path=\"./node_modules/typemoq/dist/typemoq.d.ts\" /\u003e\nimport * as TypeMoq from \"typemoq\";\n```\n\nTypeMoq requires some dependencies to run, so make sure to include them in your page before `typemoq.js`:\n\n```html\n\u003cscript src=\"https://unpkg.com/circular-json/build/circular-json\"\u003e\u003c/script\u003e\n\u003cscript src=\"https://unpkg.com/lodash\"\u003e\u003c/script\u003e\n\u003cscript src=\"https://unpkg.com/typemoq\"\u003e\u003c/script\u003e\n```\n\nAlso in your `tsconfig.json` you need to set the module target as `UMD`:\n```\n\"compilerOptions\": {\n    ...\n    \"module\": \"UMD\",\n    ...\n}\n```\n\nAt this point you should have access in your script to a global variable named `TypeMoq`.\n\n\nUsage\n-------------\n\nAfter importing TypeMoq into your project, the following types should be available:\n\nType | Description\n---- | ----\n*TypeMoq.Mock* | Used for creating 'regular' mocks (see [Create mocks](#create-mocks) and [Setup mocks](#setup-mocks))\n*TypeMoq.MockBehavior* | Used to specify how the mock should act when no expectations are defined (see [Control mock behavior](#control-mock-behavior))\n*TypeMoq.It* | Helper for matching arguments (see [Setup mocks](#setup-mocks) and [Verify expectations](#verify-expectations))\n*TypeMoq.Times* | Helper for performing verification (see [Verify expectations](#verify-expectations))\n*TypeMoq.GlobalMock* | Used to create 'global' mocks corresponding to global objects (see [Create global mocks](#create-global-mocks))\n*TypeMoq.GlobalScope* | Used to create an execution context that makes use of any specified 'global' mocks (see [Auto sandbox global mocks](#auto-sandbox-global-mocks))\n*TypeMoq.MockException* | Exception thrown internally containing debug info \n\n\n### Create mocks\n\n#### Static mocks\n\nStatic mocks can be created either from class types and constructor arguments or from existing objects, including function objects.\n\n##### Using class types and constructor arguments\n\n```typescript\n(method) TypeMoq.Mock.ofType\u003cT\u003e(targetConstructor?: {\n    new (...ctorArgs: any[]): T;\n    prototype: Object;\n}, behavior?: TypeMoq.MockBehavior, shouldOverrideTarget?: boolean, ...targetConstructorArgs: any[]): TypeMoq.IMock\u003cT\u003e\n\n(method) TypeMoq.Mock.ofType2\u003cT\u003e(targetConstructor: {\n    new (...ctorArgs: any[]): T;\n    prototype: Object;\n}, targetConstructorArgs: any[], behavior?: TypeMoq.MockBehavior, shouldOverrideTarget?: boolean): TypeMoq.IMock\u003cT\u003e\n```\n\n* *targetConstructor* - target constructor type\n* *...targetConstructorArgs* - target constructor args\n* *behavior* - mock behavior (see [Control mock behavior](#control-mock-behavior))\n* *shouldOverrideTarget* - override target properties (see [Override target properties](#override-target-properties))\n\n**Note:** During the creation of the static mock, the target object is being instantiated as a regular JavaScript object by executing the target constructor with any provided constructor args\n\nExamples:\n\n```typescript\ninterface IBar {\n  value: string;\n  anyValue: any;\n}\n\nclass Bar implements IBar {\n  value: string = '';\n  anyValue: any = undefined;\n}\n\nclass Foo {\n  constructor(private _bar: IBar) { this._bar = _bar || new Bar(); }\n  \n  get bar(): IBar { return this._bar; }\n  do(stringValue: string) { return 'Foo.do:' + stringValue; }\n  setBar(value: string) { this._bar.value = value; }\n}\n\nclass GenericFoo\u003cT\u003e {\n  private _bar: T;\n\n  constructor(barCtor?: { new (): T }, public numberValue?: number) {\n    this._bar = new barCtor(); \n  }\n\n  get bar(): T { return this._bar; }\n  do(stringValue: string) { return 'GenericFoo.do:' + stringValue + ': ' + this._bar.toString(); }\n}\n\n// Using class as constructor parameter\nconst mock: TypeMoq.IMock\u003cBar\u003e = TypeMoq.Mock.ofType(Bar);\n\n// Using class as constructor parameter and casting result to interface\nconst mock: TypeMoq.IMock\u003cIBar\u003e = TypeMoq.Mock.ofType(Bar);\n\n// Using interface as type variable and class as constructor parameter\nconst mock: TypeMoq.IMock\u003cIBar\u003e = TypeMoq.Mock.ofType\u003cIBar\u003e(Bar);\n\n// Using class as constructor parameter and constructor arguments\nconst bar = new Bar();\nconst mock: TypeMoq.IMock\u003cFoo\u003e = TypeMoq.Mock.ofType(Foo, TypeMoq.MockBehavior.Loose, bar);\n\n// Using a generic class as constructor parameter and constructor arguments\nconst mock = \u003cTypeMoq.IMock\u003cGenericFoo\u003cBar\u003e\u003e\u003eTypeMoq.Mock.ofType(GenericFoo, TypeMoq.MockBehavior.Loose, Bar, 999);\n```\n\n##### Using existing objects, including function objects\n\n```typescript\n(method) TypeMoq.Mock.ofInstance\u003cT\u003e(\n    targetInstance: T, behavior?: TypeMoq.MockBehavior, shouldOverrideTarget?: boolean): TypeMoq.IMock\u003cT\u003e\n```\n\n* *targetInstance* - target object\n* *behavior* - mock behavior (see [Control mock behavior](#control-mock-behavior))\n* *shouldOverrideTarget* - override target properties (see [Override target properties](#override-target-properties))\n\n**Note:** To create the static mock, the provided target object is replaced by a deep clone which is accesible through the `.target` property of the resulting mock object\n\nExamples:\n\n```typescript\nfunction someFunc() {\n  return \"someFunc was called\";\n}\n\nfunction someFuncWithArgs(a: any, b: any, c: any) {\n  return \"someFuncWithArgs was called\";\n}\n\n// From an existing object\nconst bar = new Bar();\nconst mock: TypeMoq.IMock\u003cBar\u003e = TypeMoq.Mock.ofInstance(bar);\n\n// Or from function objects\nconst mock1: TypeMoq.IMock\u003c() =\u003e string\u003e = TypeMoq.Mock.ofInstance(someFunc);\nconst mock2: TypeMoq.IMock\u003c(a: any, b: any, c: any)=\u003estring\u003e = TypeMoq.Mock.ofInstance(someFuncWithArgs);\n```\n\n#### Dynamic mocks\n\n**Important:** Dynamic mocking requires the runtime (browser or node.js) to support the `Proxy` global object added in ECMAScript 6. If `Proxy` is not detected, TypeMoq is going to throw a MockException.\n\nA dynamic mock is created by specifying just a type parameter and some optional args:\n\n```typescript\n(method) TypeMoq.Mock.ofType\u003cT\u003e(targetConstructor?: {\n    new (...ctorArgs: any[]): T;\n    prototype: Object;\n}, behavior?: TypeMoq.MockBehavior, shouldOverrideTarget?: boolean): TypeMoq.IMock\u003cT\u003e\n```\n\n* *targetConstructor* - always `undefined` for dynamic mocks\n* *behavior* - mock behavior (see [Control mock behavior](#control-mock-behavior))\n* *shouldOverrideTarget* - override target properties (see [Override target properties](#override-target-properties))\n\n**Note:** While creating the dynamic mock, the target object is **not** instantiated by executing the constructor of the provided type parameter\n\nThe following type parameters are supported:\n\n* `Function` (as the type of a [function object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function))\n\n```typescript\n// Using Function as type parameter\nconst mock: TypeMoq.IMock\u003cFunction\u003e = TypeMoq.Mock.ofType\u003cFunction\u003e();\n```\n\n* a class type\n\n```typescript\n// Using the 'instance' side of the class as type parameter\nconst mock: TypeMoq.IMock\u003cBar\u003e = TypeMoq.Mock.ofType\u003cBar\u003e();\n\n// Specifying mock behavior\nconst mock: TypeMoq.IMock\u003cFoo\u003e = TypeMoq.Mock.ofType\u003cFoo\u003e(undefined, TypeMoq.MockBehavior.Loose);\n```\n\n* a constructor function\n\n```typescript\n// Using the 'static' side of the class as type parameter\nconst mock: TypeMoq.IMock\u003ctypeof Bar\u003e = TypeMoq.Mock.ofType\u003ctypeof Bar\u003e();\n```\n\n* an interface type\n\n```typescript\n// Using an interface as type parameter\nconst mock: TypeMoq.IMock\u003cIBar\u003e = TypeMoq.Mock.ofType\u003cIBar\u003e();\n```\n\n\nAs opposed to static mocks, dynamic mocks have some limitations:\n \n* No partial mocking\n* No embedded mocks passed as constructor arguments\n* Properties return by default a `function` object and not `undefined`\n\n```typescript\ninterface IThing {\n  getA(a: string): string;\n  getB(b: number): number;\n  getC(): boolean;\n  valueA: string;\n}\n\nconst mock: TypeMoq.IMock\u003cIThing\u003e = TypeMoq.Mock.ofType\u003cIThing\u003e();\n\nexpect(mock.object.getA(\"abc\")).to.be.undefined;\nexpect(mock.object.getB(123)).to.be.undefined;\nexpect(mock.object.getC()).to.be.undefined;\nexpect(mock.object.valueA).to.be.a(\"function\");\n```\n\nAs a workaround you may set the property to return `undefined`:\n\n```typescript\nmock.setup(x =\u003e x.valueA).returns(() =\u003e undefined);\n\nexpect(mock.object.valueA).to.be.undefined;\n```\n\nThis limitation also impacts the scenario where a mocked object is passed to `Promise.resolve`. To be able to handle such scenario, the mocked object must be set as a thenable (i.e. has a \"then\" method) by returning `undefined` or another value:\n\n```typescript\nmock.setup((x: any) =\u003e x.then).returns(() =\u003e undefined);\n\nPromise.resolve(mock.object)\n  .then(x =\u003e {\n    expect(x).eql(mock.object);\n  });\n```\n\n\n#### Mocks type\n\nMocks (created in any of the ways listed above) have the type `IMock\u003cT\u003e` and expose a couple important properties:\n\n* `(property) TypeMoq.IMock\u003cT\u003e.object: T` - the actual mock object (that has the same type T as the class or object being mocked)\n* `(property) TypeMoq.IMock\u003cT\u003e.target: T` - the underlying object being mocked\n\n\n### Setup mocks\n\nMocks allow to match functions, methods and properties and setup return callbacks or exceptions to throw.\n\n```typescript\n(method) TypeMoq.IMock\u003cT\u003e.setup\u003cTResult\u003e(\n    expression: (x: T) =\u003e TResult): TypeMoq.MethodCallReturn\u003cT, TResult\u003e\n```\n\n`setup` accepts a function (also referred as 'matcher') taking as input argument the type being mocked and as body the value/property/method (with arguments if that's the case) to match.\n\n##### Parameter matchers\n\nMatcher | Description\n---- | ----\n```TypeMoq.It.isValue\u003cT\u003e(x: T)``` | Performs deep comparison against the provided object or basic value\n```TypeMoq.It.isObjectWith\u003cT\u003e(x: Object)``` | Performs partial deep comparison against the provided object\n```TypeMoq.It.isAny()``` | Matches any type\n```TypeMoq.It.isAnyObject\u003cT\u003e(x: Ctor\u003cT\u003e)``` | Matches any object compatible with the provided type\n```TypeMoq.It.isAnyString()``` | Matches any string\n```TypeMoq.It.isAnyNumber()``` | Matches any number\n```TypeMoq.It.is\u003cT\u003e(predicate: IFunc2\u003cT, boolean\u003e)``` | Performs comparison using the provided predicate\n\nIf no matcher is specified then an implicit matcher is considered that performs strict equality deep comparison, equivalent to `TypeMoq.It.is(x =\u003e _.isEqual(x, a))`.\n\n##### Matching functions\n\n```typescript\n// Match a no args function\nconst mock: TypeMoq.IMock\u003c() =\u003e string\u003e = TypeMoq.Mock.ofInstance(someFunc);\nmock.setup(x =\u003e x()).returns(() =\u003e \"At vero eos et accusamus\");\n\n// Match a function with args\nconst mock: TypeMoq.IMock\u003c(a: any, b: any, c: any) =\u003e string\u003e = TypeMoq.Mock.ofInstance(someFuncWithArgs);\nmock.setup(x =\u003e x(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny())).returns(() =\u003e \"At vero eos et accusamus\");\n```\n\n##### Matching methods\n\n```typescript\nclass Doer {\n  doVoid(): void { }\n  doNumber(n?: number): number { return n || 101; }\n  doString(s?: string): string { return s || 'xyz'; }\n  doObject(o?: Object): Object { return o || new Object(); }\n  doBar(b?: Bar): Bar { return b; }\n}\n\nconst mock = TypeMoq.Mock.ofType(Doer);\n\n// Match a no args method\nmock.setup(x =\u003e x.doNumber());\n\n// Match a method with explicit number value params\nmock.setup(x =\u003e x.doNumber(TypeMoq.It.isValue(321)));\n\n// Match a method with implicit number value params\nmock.setup(x =\u003e x.doNumber(321));\n\n// Match a method with explicit string value params\nmock.setup(x =\u003e x.doString(TypeMoq.It.isValue(\"abc\")));\n\n// Match a method with implicit string value params\nmock.setup(x =\u003e x.doString(\"abc\"));\n\n// Match a method with object value params\nconst bar = new Bar();\nmock.setup(x =\u003e x.doObject(TypeMoq.It.isAnyObject(Bar)));\n\n// Match a method with implicit object value params\nconst anObject = {};\nmock.setup(x =\u003e x(anObject)).returns(() =\u003e 123);\nexpect(mock.object(anObject)).to.eq(123);\n\n// Match a method with any string params\nmock.setup(x =\u003e x.doString(TypeMoq.It.isAnyString()));\n\n// Match a method with any number params\nmock.setup(x =\u003e x.doNumber(TypeMoq.It.isAnyNumber()));\n\n// Match a method with any interface/class params\nmock.setup(x =\u003e x.doBar(TypeMoq.It.isAnyObject(Bar)));\n\n// Match a method by a param predicate \nconst bar1 = new Bar();\nbar1.value = \"Ut enim ad minim veniam\";\nconst bar2 = new Bar();\nconst mock = TypeMoq.Mock.ofType(Doer);\n\nmock.setup(x =\u003e x.doBar(TypeMoq.It.is((x: Bar) =\u003e x.value === \"Ut enim ad minim veniam\"))).returns(() =\u003e bar2);\n```\n\nTo be able to match the static methods of some class, you would need to create a dynamic mock of the type of the class itself. E.g.\n\n```typescript\nclass Greeter {\n  private static _instance: Greeter | null;\n  static instance(): Greeter {\n    if (!this._instance) {\n      this._instance = new Greeter();\n    }\n    return this._instance;\n  } \n    \n  greet(): string {\n    return 'Hello';\n  }\n}\n\nconst greeter = Greeter.instance();\nconst mock: TypeMoq.IMock\u003ctypeof Greeter\u003e = TypeMoq.Mock.ofType\u003ctypeof Greeter\u003e();\n\nmock.setup(x =\u003e x.instance()).returns(() =\u003e greeter);\n\nexpect(mock.object.instance()).to.eq(greeter);\n```\n\n##### Matching properties\n\n```typescript\nclass FooWithPublicGetterAndSetter {\n  private _foo: string;\n  public get foo(): string { return this._foo; }\n  public set foo(value: string) { this._foo = value; }\n}\n\n// Match a property getter\nconst mock = TypeMoq.Mock.ofType(FooWithPublicGetterAndSetter);\nmock.setup(x =\u003e x.foo);\n\n// Match a property setter\nmock.object.foo = \"Lorem ipsum dolor sit amet\";\nmock.verify(x =\u003e x.foo = TypeMoq.It.isValue(\"Lorem ipsum dolor sit amet\"), Times.atLeastOnce());\n```\n\nTo be able to match a property make sure the property is initialized.\nOtherwise the TypeScript compiler will omit the uninitialized property from the emitted JavaScript and hence TypeMoq will throw a MockException with an 'invalid setup expression' message.\n\n```typescript\nclass Baz {\n  value: string = '';\n  anyValue: any;\n}\n\nconst mock = TypeMoq.Mock.ofType(Baz);\nmock.setup(x =\u003e x.value);       // OK\nmock.setup(x =\u003e x.anyValue);    // throws MockException - invalid setup expression\n```\n\n##### Matching objects\n\n```typescript\ninterface Baz {\n  bar: string\n  jaz: number  \n}\n\nclass FooWithObjectArgMethod {\n  private _foo: Object\n  public foo(value: Object): void { }\n}\n\nconst mock = TypeMoq.Mock.ofType(FooWithObjectArgMethod);\n\n// Match object deeply\nmock.setup(x =\u003e x.foo(TypeMoq.It.isValue({ bar: 'hello', jaz: 42 })));\n\n// Match object partially\nmock.setup(x =\u003e x.foo(TypeMoq.It.isObjectWith({ jaz: 42 })));\n```\n\nFor the predicate based matcher, `TypeMoq.It.is\u003cT\u003e(predicate: IFunc2\u003cT, boolean\u003e)`, the argument of the predicate is a deep clone of the target argument, thus for doing object equality comparison, `===` should be replaced by `_.isEqual`.\n\n```typescript\ninterface BeanParams {\n  colour: string\n}\n\ninterface Service {\n  getBeans(params: BeanParams): string;\n}\n\nconst service = TypeMoq.Mock.ofType\u003cService\u003e();\nconst beanParams: BeanParams = { colour: 'red' };\n\n// Wrong way of doing strict object comparison\nservice.setup(x =\u003e x.getBeans(TypeMoq.It.is\u003cBeanParams\u003e(x =\u003e x === beanParams))).returns(() =\u003e 'success');\nexpect(service.object.getBeans(beanParams)).to.not.eq('success');\n\n// Right way of doing strict object comparison\nservice.setup(x =\u003e x.getBeans(TypeMoq.It.is\u003cBeanParams\u003e(x =\u003e _.isEqual(x, beanParams)))).returns(() =\u003e 'success');\nservice.setup(x =\u003e x.getBeans(beanParams)).returns(() =\u003e 'success');  // Short form equivalent to the explicit form above\nexpect(service.object.getBeans(beanParams)).to.eq('success');\n```\n\n##### Attaching return callbacks\n\n```typescript\n(method) TypeMoq.IReturns\u003cT, TResult\u003e.returns(\n    valueFunction: (...x: any[]) =\u003e TResult): TypeMoq.IReturnsResult\u003cT\u003e\n```\n\nThe callback attached to `.returns` has the same signature as the matching function/method.\n\nAlso the callback gets called with the arguments passed to the matching function/method and it must have the same return type, making possible the following:\n\n```typescript\nmock.setup(x =\u003e x.doString(\"abc\")).returns((s: string) =\u003e s.toUpperCase());\n```\n\n##### Attaching exceptions to throw\n\n```typescript\n(method) TypeMoq.IThrows.throws\u003cT extends Error\u003e(exception: T): TypeMoq.IThrowsResult\n```\n\nExample:\n\n```typescript\nmock.setup(...).throws(new CustomException());\n```\n\n\n### Attach callbacks\n\n```typescript\n(method) TypeMoq.ICallback\u003cT, TResult\u003e.callback(\n    action: () =\u003e void): TypeMoq.IReturnsThrows\u003cT, TResult\u003e\n\n(method) TypeMoq.ICallback\u003cT, TResult\u003e.callback(\n    action: (x: T) =\u003e void): TypeMoq.IReturnsThrows\u003cT, TResult\u003e\n```\n\nAttached callbacks are called before the `.returns` callback or `.throws` get called, and they have similar signature and behavior to `.returns` callbacks.\n\nExamples:\n\n```typescript\nconst mock = TypeMoq.Mock.ofType(Doer);\nlet called1, called2 = false;\nlet numberArg: number;\n\nmock.setup(x =\u003e x.doString(TypeMoq.It.isAnyString())).callback(() =\u003e called1 = true).returns(s =\u003e s.toUpperCase());\nmock.setup(x =\u003e x.doNumber(TypeMoq.It.isAnyNumber())).callback(n =\u003e { numberArg = n; called2 = true; }).returns(n =\u003e n + 1);\n```\n\n\n### Record and replay\n\nMocks allow to \"record\" and \"replay\" one or more setups for the same matching function, method or property.\n\n* If a single setup is recorded then at replay it is always executed:\n```typescript\nconst mock = TypeMoq.Mock.ofInstance(() =\u003e -1);\n\n// record\nmock.setup(x =\u003e x()).returns(() =\u003e 0);\n\n// replay\nexpect(mock.object()).to.eq(0);\nexpect(mock.object()).to.eq(0);\nexpect(mock.object()).to.eq(0);\n```\n\n* If more setups are recorded then at replay they are executed in the order of registration:\n```typescript\nconst mock = TypeMoq.Mock.ofInstance(() =\u003e -1);\n\n// record\nmock.setup(x =\u003e x()).returns(() =\u003e 0);\nmock.setup(x =\u003e x()).returns(() =\u003e 1);\nmock.setup(x =\u003e x()).returns(() =\u003e 2);\n\n// replay\nexpect(mock.object()).to.eq(0);\nexpect(mock.object()).to.eq(1);\nexpect(mock.object()).to.eq(2);\nexpect(mock.object()).to.eq(undefined);\n```\n\nIn the latter case, when there are no more recorded setups left to play, the mock starts returning default values or raises MockException if `MockBehavior.Strict` (see [Control mock behavior](#control-mock-behavior)).\n\n\n### Reset mocks\n\n```typescript\n(method) TypeMoq.IMock\u003cT\u003e.reset(): void\n```\n\nCalling `.reset()` on a mock returns the mock to its initial state by removing any previous setups.\n\n\n### Control mock behavior\n\n##### Using MockBehavior\n\nAt mock creation, use the optional `behavior` argument with value:\n\n* `MockBehavior.Loose` (default) - never throws when no corresponding setup is found and just returns default values\n* `MockBehavior.Strict` - raises exceptions for anything that doesn't have a corresponding setup\n\n```typescript\nconst mock = TypeMoq.Mock.ofType(Doer, TypeMoq.MockBehavior.Strict);\n```\n\n##### Partial mocking\n\n```typescript\n(property) TypeMoq.IMock\u003cT\u003e.callBase: boolean\n```\n\nWhen the mock property `callBase` is set to `true`, if there's no overriding setup the mock invokes the object being mocked.\n\n```typescript\nmock.callBase = true;\n```\n\nThe default value of `callBase` is `false`, so by default when there's no overriding setup the mock returns `undefined`.\n\n\n### Override target properties\n\nAt mock creation, use the optional `shouldOverrideTarget` argument with value:\n\n* `true` (default) - mock setups are going to be applied to the target object\n* `false` - mock setups are **not** going to be applied to the target object\n\nTo be able to use the target object inside `.returns`, you need to choose **not** to override the target properties:\n\n```typescript\nconst targetInstance = {\n    n: 100,\n    getValue() {\n        return this.n;\n    },\n    setValue(n) {\n        this.n = n;\n    }\n};\nconst mock = TypeMoq.Mock.ofInstance(targetInstance, undefined, false);\n\nmock.setup(x =\u003e x.getValue()).returns(() =\u003e mock.target.getValue());\n\nexpect(mock.object.getValue()).equal(100);\n```\n\n\n### Verify expectations\n\n```typescript\n(method) TypeMoq.IVerifies.verifiable(times?: TypeMoq.Times): void\n```\n\nExpectations can be verified either one by one or all at once by marking matchers as verifiable.\n\n##### Expectations\n\nExpectation | Description\n---- | ----\n```TypeMoq.Times.exactly(n: number)``` | Called exactly `n` times\n```TypeMoq.Times.never()``` | Never called\n```TypeMoq.Times.once()``` | Called once\n```TypeMoq.Times.atLeast(n: number)``` | Called at least `n` times\n```TypeMoq.Times.atMost(n: number)``` | Called at most `n` times\n```TypeMoq.Times.atLeastOnce()``` | Called at least once (default value)\n```TypeMoq.Times.atMostOnce()``` | Called at most once\n\n##### Verify expectations one by one\n\n```typescript\n(method) TypeMoq.IMock\u003cT\u003e.verify\u003cTResult\u003e(\n    expression: (x: T) =\u003e TResult, times: TypeMoq.Times): void\n```\n\nTo verify an expectation you can use the `verify` method and specify a matching function and an expectation.\n\nExamples:\n\n```typescript\n// Verify that a no args function was called at least once\nconst mock: TypeMoq.IMock\u003c() =\u003e string\u003e = TypeMoq.Mock.ofInstance(someFunc);\nmock.object();\nmock.verify(x =\u003e x(), TypeMoq.Times.atLeastOnce());\n\n// Verify that a function with args was called at least once\nconst mock: TypeMoq.IMock\u003c(a: any, b: any, c: any) =\u003e string\u003e = TypeMoq.Mock.ofInstance(someFuncWithArgs);\nmock.object(1, 2, 3);\nmock.verify(x =\u003e x(TypeMoq.It.isAnyNumber(), TypeMoq.It.isAnyNumber(), TypeMoq.It.isAnyNumber()), TypeMoq.Times.atLeastOnce());\n\n// Verify that no args method was called at least once\nconst mock = TypeMoq.Mock.ofType(Doer);\nmock.object.doVoid();\nmock.verify(x =\u003e x.doVoid(), TypeMoq.Times.atLeastOnce());\n\n// Verify that method with params was called at least once\nconst mock = TypeMoq.Mock.ofType(Doer);\nmock.object.doString(\"Lorem ipsum dolor sit amet\");\nmock.verify(x =\u003e x.doString(TypeMoq.It.isValue(\"Lorem ipsum dolor sit amet\")), TypeMoq.Times.atLeastOnce());\n\n// Verify that value getter was called at least once\nconst mock = TypeMoq.Mock.ofType(Bar);\nmock.object.value;\nmock.verify(x =\u003e x.value, TypeMoq.Times.atLeastOnce());\n\n// Verify that value setter was called at least once\nconst mock = TypeMoq.Mock.ofType(Bar);\nmock.object.value = \"Lorem ipsum dolor sit amet\";\nmock.verify(x =\u003e x.value = TypeMoq.It.isValue(\"Lorem ipsum dolor sit amet\"), TypeMoq.Times.atLeastOnce());\n```\n\n**Note:**\n\n* When constructing a mock, it is allowed to pass mock objects as arguments and later verify expectations on them. E.g.: \n\n```typescript\nconst mockBar = TypeMoq.Mock.ofType(Bar);\nconst mockFoo = TypeMoq.Mock.ofType(Foo, TypeMoq.MockBehavior.Loose, mockBar.object);\nmockFoo.callBase = true;\n\nmockFoo.object.setBar(\"Lorem ipsum dolor sit amet\");\n\nmockBar.verify(x =\u003e x.value = TypeMoq.It.isValue(\"Lorem ipsum dolor sit amet\"), TypeMoq.Times.atLeastOnce());\n```\n\n* For static mocks, TypeMoq is able to verify any inner calls inside regular functions but not inside lambda ones. E.g.:\n\n```typescript\nclass FooBar {\n  register(): void {\n    this.canExecute();\n  }\n\n  registerLambda = () =\u003e {\n    this.canExecute();\n  }\n\n  canExecute(): void {\n    console.log(\"FooBar.canExecute() was called\");\n  }\n}\n\nconst mock: TypeMoq.IMock\u003cFooBar\u003e = TypeMoq.Mock.ofType(FooBar);\nmock.callBase = true;\n\nmock.object.register();\nmock.object.registerLambda(); // Function calls cannot be verified inside a lambda\n\nmock.verify(x =\u003e x.canExecute(), TypeMoq.Times.once());\n```\n\n##### Verify all expectations at once\n\n```typescript\n(method) TypeMoq.IMock\u003cT\u003e.verifyAll(): void\n```\n\nInstead of verifying one expectation at a time, you may specify the expectation at setup time by calling `verifiable(times: TypeMoq.Times)` and then `verifyAll()` to check all expectations.\n\nThe default value of the `times` parameter is equal to `TypeMoq.Times.once()`.\n\n```typescript\nmock.setup(x =\u003e x.doNumber(999)).verifiable(); // implicitly TypeMoq.Times.once()\nmock.setup(x =\u003e x.doString(TypeMoq.It.isAny())).verifiable(TypeMoq.Times.exactly(2));\nmock.setup(x =\u003e x.doVoid()).verifiable(TypeMoq.Times.atMostOnce());\n\nmock.object.doVoid();\nmock.object.doString(\"Lorem ipsum dolor sit amet\");\nmock.object.doString(\"Ut enim ad minim veniam\");\nmock.object.doNumber(999);\n\nmock.verifyAll();\n```\n\nWhen mock behavior is `TypeMoq.MockBehavior.Strict`, every call to `.setup()` automatically calls `.verifiable()` behind the scenes, as the default.\n\n```typescript\nconst mock = TypeMoq.Mock.ofType(Doer, TypeMoq.MockBehavior.Strict);\n\nmock.setup(x =\u003e x.doNumber(999)); // implicitly TypeMoq.Times.once()\nmock.setup(x =\u003e x.doVoid()).verifiable(TypeMoq.Times.atMostOnce());\n\nmock.object.doVoid();\nmock.object.doNumber(999);\n\nmock.verifyAll();\n```\n\n##### Verify expectation invocation order\n\nExpectation invocation order | Description\n---- | ----\n```TypeMoq.ExpectedCallType.InAnyOrder``` | Only call count considered (default value) \n```TypeMoq.ExpectedCallType.InSequence``` | Both call count and order considered\n\n```typescript\nconst mock = TypeMoq.Mock.ofInstance((x: number) =\u003e { });\n\nmock.setup(x =\u003e x(1)).verifiable(TypeMoq.Times.once(), TypeMoq.ExpectedCallType.InSequence);\nmock.setup(x =\u003e x(2)).verifiable(TypeMoq.Times.once(), TypeMoq.ExpectedCallType.InSequence);\n\nmock.object(2);\nmock.object(1);\n\nmock.verifyAll();  // it should throw MockException\n```\n\n\n### Create global mocks\n\n#### Static global mocks\n\nStatic global mocks are created by specifying a class type or an existing object, similar to regular static mocks.\n\nYou may also specify a container object for the type/object being mocked.\n\nFor browsers the top global object is the `window` object, which is the default `container` value in `TypeMoq.GlobalMock`.\nFor node.js the top global object is the `global` object.\n\n##### Using class types\n\n```typescript\n(method) TypeMoq.GlobalMock.ofType\u003cT\u003e(targetConstructor: {\n    new (): T;\n    prototype: Object;\n}, container?: Object, behavior?: TypeMoq.MockBehavior): TypeMoq.IGlobalMock\u003cT\u003e\n```\n\nDue to browser security limitations, global mocks created by specifying class type cannot have constructor arguments.\n\nExamples:\n\n```typescript\n// global scope\n\ninterface IGlobalBar {\n  value: string;\n}\n\nclass GlobalBar implements IGlobalBar {\n  value: string = '';\n}\n\n// Create an instance using class as ctor parameter\nconst mock: TypeMoq.IGlobalMock\u003cGlobalBar\u003e = TypeMoq.GlobalMock.ofType(GlobalBar, global);\n\n// Create an instance using class as ctor parameter and casting result to interface\nconst mock: TypeMoq.IGlobalMock\u003cIGlobalBar\u003e = TypeMoq.GlobalMock.ofType(GlobalBar, global);\n\n// Create an instance using interface as type variable and class as ctor parameter\nconst mock: TypeMoq.IGlobalMock\u003cIGlobalBar\u003e = TypeMoq.GlobalMock.ofType\u003cIGlobalBar\u003e(GlobalBar, global);\n\n// Create an instance of 'XmlHttpRequest' global type\nconst mock = TypeMoq.GlobalMock.ofType(XMLHttpRequest, global);\n```\n\n##### Using existing objects, including function objects\n\n```typescript\n(method) TypeMoq.GlobalMock.ofInstance\u003cT\u003e(\n    targetInstance: T, globalName?: string, container?: Object, behavior?: TypeMoq.MockBehavior): TypeMoq.IGlobalMock\u003cT\u003e\n```\n\nWhen creating mock instances out of global objects (such as `window.localStorage`), you should provide the name of the global object (*\"localStorage\"* in this case) as the second parameter.\n\nExamples:\n\n```typescript\n// Create an instance using class as ctor parameter and ctor args\nconst bar = new Bar();\nconst foo = new Foo(bar);\nconst mock: TypeMoq.IGlobalMock\u003cFoo\u003e = TypeMoq.GlobalMock.ofInstance(foo);\n\n// Create an instance using a generic class as ctor parameter and ctor args\nconst foo = new GenericFoo(Bar);\nconst mock: TypeMoq.IGlobalMock\u003cGenericFoo\u003cBar\u003e\u003e = TypeMoq.GlobalMock.ofInstance(foo);\n\n// Create an instance from an existing object\nconst bar = new GlobalBar();\nconst mock: TypeMoq.IGlobalMock\u003cGlobalBar\u003e = TypeMoq.GlobalMock.ofInstance(bar);\n\n// Create an instance from a function object\nconst mock1: TypeMoq.IGlobalMock\u003c() =\u003e string\u003e = TypeMoq.GlobalMock.ofInstance(someGlobalFunc);\nconst mock2: TypeMoq.IGlobalMock\u003c(a: any, b: any, c: any) =\u003e string\u003e = TypeMoq.GlobalMock.ofInstance(someGlobalFuncWithArgs);\n\n// Create an instance from 'window.localStorage' global object\nconst mock = TypeMoq.GlobalMock.ofInstance(localStorage, \"localStorage\");\n```\n\n#### Dynamic global mocks\n\n```typescript\n(method) TypeMoq.GlobalMock.ofType2\u003cT\u003e(\n    globalName: string, container?: Object, behavior?: TypeMoq.MockBehavior): TypeMoq.IGlobalMock\u003cT\u003e\n```\n\nDynamic global mocks are created by specifying a type parameter and the name of the global object as the first constructor argument.\n\n```typescript\n// Create an instance using a class as type parameter\nconst mock: TypeMoq.IGlobalMock\u003cGlobalBar\u003e = TypeMoq.GlobalMock.ofType2\u003cGlobalBar\u003e(\"GlobalBar\", global);\n\n// Create an instance using an interface as type parameter\nconst mock: TypeMoq.IGlobalMock\u003cIGlobalBar\u003e = TypeMoq.GlobalMock.ofType2\u003cIGlobalBar\u003e(\"IGlobalBar\", global);\n\n// Create an instance of 'XmlHttpRequest' global type\nconst mock = TypeMoq.GlobalMock.ofType2\u003cXMLHttpRequest\u003e(\"XMLHttpRequest\", global);\n```\n\nCompared to static global mocks, dynamic global mocks suffer from the same limitations as regular dynamic mocks.\n\n\n### Auto sandbox global mocks\n\n```typescript\n(method) TypeMoq.GlobalScope.using(\n    ...args: TypeMoq.IGlobalMock\u003cany\u003e[]): TypeMoq.IUsingResult\n\n(method) TypeMoq.IUsingResult.with(action: () =\u003e void): void\n```\n\nReplacing and restoring global class types and objects is done automagically by combining global mocks with global scopes.\n\nExamples:\n\n```typescript\n// global scope\n\nfunction someGlobalFunc() {\n  return \"someGlobalFunc was called\";\n}\n\nfunction someGlobalFuncWithArgs(a: any, b: any, c: any) {\n  return \"someGlobalFuncWithArgs was called\";\n}\n\n// Global no args function is auto sandboxed\nconst mock = TypeMoq.GlobalMock.ofInstance(someGlobalFunc);\nTypeMoq.GlobalScope.using(mock).with(() =\u003e {\n    someGlobalFunc();\n    someGlobalFunc();\n});\n\n// Global function with args is auto sandboxed\nconst mock = TypeMoq.GlobalMock.ofInstance(someGlobalFuncWithArgs);\nTypeMoq.GlobalScope.using(mock).with(() =\u003e {\n    someGlobalFuncWithArgs(1,2,3);\n    someGlobalFuncWithArgs(\"1\",\"2\",\"3\");\n    someGlobalFuncWithArgs(1, 2, 3);\n);\n\n// Global object is auto sandboxed\nconst mock = TypeMoq.GlobalMock.ofType(GlobalBar);\nTypeMoq.GlobalScope.using(mock).with(() =\u003e {\n    const bar1 = new GlobalBar();\n    bar1.value;\n    bar1.value;\n});\n\n// 'window.XmlHttpRequest' global object is auto sandboxed\nconst mock = TypeMoq.GlobalMock.ofType(XMLHttpRequest);\nTypeMoq.GlobalScope.using(mock).with(() =\u003e {\n    const xhr1 = new XMLHttpRequest();\n    xhr1.open(\"GET\", \"http://www.typescriptlang.org\", true);\n    xhr1.send();\n    mock.verify(x =\u003e x.send(), TypeMoq.Times.exactly(1));\n});\nconst xhr2 = new XMLHttpRequest();\nxhr2.open(\"GET\", \"http://www.typescriptlang.org\", true);\nxhr2.send();\nmock.verify(x =\u003e x.send(), TypeMoq.Times.exactly(1));\n\n// 'window.localStorage' global object is auto sandboxed\nconst mock = TypeMoq.GlobalMock.ofInstance(localStorage, \"localStorage\");\nmock.setup(x =\u003e x.getItem(TypeMoq.It.isAnyString())).returns((key: string) =\u003e \"[]\");\nTypeMoq.GlobalScope.using(mock).with(() =\u003e {\n    expect(localStorage.getItem(\"xyz\")).to.eq(\"[]\");\n});\nlocalStorage.setItem(\"xyz\", \"Lorem ipsum dolor sit amet\");\nexpect(localStorage.getItem(\"xyz\")).to.eq(\"Lorem ipsum dolor sit amet\");\n```\n\n**Note:** \nInside the scope of a TypeMoq.GlobalScope, when constructing objects from global functions/class types which are being replaced by mocks, the constructor always returns the mocked object (of corresponding type) passed in as argument to the `TypeMoq.GlobalScope.using` function\n\n\n## License\n\n[MIT](https://github.com/florinn/typemoq/blob/master/LICENSE)\n","funding_links":[],"categories":["TypeScript","Table of Contents","Built with TypeScript"],"sub_categories":["Libraries"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflorinn%2Ftypemoq","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflorinn%2Ftypemoq","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflorinn%2Ftypemoq/lists"}