问题
I have an object that I am mocking up for unit testing. Essentially in my test file I mock it up as follows:
var mockObject = {
mockMethod1 : function() {return true},
mockMethod2 : function() {return true}
};
beforeEach(module('myModule') , function ($provide) {
$provide.value('realObject',mockObject);
});
The way i understand it is that as I test functionality in my module etc... anywhere that references the "realObject" will use my "mockObject"
My issue is that I have made multiple js files for testing and I do not want to define my "mockObject" in each one of them ... nor do i want to maintain it in any more places than i have too.
Is there a way to move my "mockObjact" to a seperate file that gets included in karma.conf.js that will make the "mockObject" available for injection into any of my test files ..... Im thinking along the lines of how you inject $rootScope
回答1:
You can create a global beforeEach function if it is written outside the context of a specific suite, but still executed by Jasmine, e.g. create a custom file to load by Karma and write your beforeEach function there without enclosing it in a describe function.
Example:
var myGlobal;
beforeEach(function() {
// This will run before any it function.
// Resetting a global state so the change in this function is testable
myGlobal = 10
});
describe('first suite', function(){
it('is a test', function(){
expect(myGlobal).toBe(10);
// Set the value to show that beforeEach is executed for each it function
myGlobal = 20;
expect(myGlobal).toBe(20);
});
it('is another test', function(){
expect(myGlobal).toBe(10);
myGlobal = 30;
expect(myGlobal).toBe(30);
});
});
describe('second suite', function(){
it('is a test', function(){
expect(myGlobal).toBe(10);
});
});
See fiddle here
回答2:
You could build a service that houses your mock, and inject that service in each test file.
beforeEach(inject(function($rootScope, $controller, yourMockSvc) {
appScope = $rootScope.$new();
appCtrl = $controller('AppController', {
$scope: appScope,
yourSvc: yourMockSvc
});
}));
回答3:
Just define your mock object inside of another file and export it. You should be able to use it in any file.
来源:https://stackoverflow.com/questions/22869822/globally-mock-object-in-angularjs-for-jasmine-karma-testing