©
Dieses Dokument verwendetPHP-Handbuch für chinesische WebsitesFreigeben
注意: This function is also published on window for easy access.
The inject function wraps a function into an injectable function. The inject() creates new instance of $injector per test, which is then used for resolving references.
Often, we would like to inject a reference once, in abeforeEach()
block and reuse this in multipleit()
clauses. To be able to do this we must assign the reference to a variable that is declared in the scope of thedescribe()
block. Since we would, most likely, want the variable to have the same name of the reference we have a problem, since the parameter to theinject()
function would hide the outer variable.
To help with this, the injected parameters can, optionally, be enclosed with underscores. These are ignored by the injector when the reference name is resolved.
例如,the parameter_myService_
would be resolved as the referencemyService
. Since it is available in the function body asmyService, we can then assign it to a variable defined in an outer scope.
// Defined out reference variable outsidevarmyService;// Wrap the parameter in underscoresbeforeEach(inject(Function(_myService_){myService=_myService_;}));// Use myService in a series of tests.it('makes use of myService',Function(){myService.doStuff();});
参见 angular.mock.module
Example of what a typical jasmine tests looks like with the inject method.
angular.module('myApplicationModule',[]).value('mode','app').value('version','v1.0.1');describe('MyApp',Function(){// You need to load modules that you want to test,// it loads only the "ng" module by default.beforeEach(module('myApplicationModule'));// inject() is used to inject arguments of all given functionsit('should provide a version',inject(Function(mode,version){expect(version).toEqual('v1.0.1');expect(mode).toEqual('app');}));// The inject and module method can also be used inside of the it or beforeEachit('should override a version and test the new version is injected',Function(){// module() takes functions or strings (module aliases)module(Function($provide){$provide.value('version','overridden');// override version here});inject(Function(version){expect(version).toEqual('overridden');});});});
angular.mock.inject(fns);
参数 | 类型 | 详述 |
---|---|---|
fns | ...Function | any number of functions which will be injected using the injector. |