简体   繁体   English

如何模拟json数据进行单元测试?

[英]how to mock json data for unit testing?

I have a function called getTodaysHours() in my controller that I would like to test. 我要测试的控制器中有一个名为getTodaysHours()的函数。 I was wondering if I can mock the JSON data below in my unit testing spec? 我想知道是否可以在我的单元测试规范中模拟下面的JSON数据?

describe('vendor controller', () => {
    let vm;

    beforeEach(angular.mock.module('thcmaps-ui'));
    beforeEach(inject(($controller) => {
        vm = $controller('VendorController');
        vm.data = {"_id":"56b54f9368e685ca04aa0b87","lat_lon":"33.713018,-117.841101",...}
    }));

    it('should state store hours for today', () => {
        console.log(vm.data);
        expect(1).toEqual(1);
    });
});

vendor.controller 供应商控制器

export class VendorController {
    constructor($rootScope, data, event, toastr, moment, _, distanceService, vendorDataService, userDataService, stateManagerService) {
        'ngInject';
        //deps
        this.$rootScope = $rootScope;
        this.toastr = toastr;
        this._ = _;
        this.userDataService = userDataService;
        this.vendorDataService = vendorDataService;
        this.stateManagerService = stateManagerService;
        this.event = event;

        //bootstrap
        data.isDeepLink = true;
        this.data = data;
        this.data.last_update = moment(this.data.updated_at).format('MM/DD/YY h:mm A');
        this.data.distance = distanceService.getDistance(this.data.loc.lng, this.data.loc.lat);
        this.data.todaysHours = this.getTodaysHours();
        this.data.rating_num = Math.floor(data.rating);


        this.hasReviewed = (userDataService.user.reviewed[data._id]) ? true : false;
        this.isGrid = false;
        this.isSearching = false;
        this.hideIntro = true;
        this.menuCollapsed = true;
        this.filterMenuCollapsed = true;

        this.selectedCategory = 'All';
        this.todaysHours = '';
        this.type = '';
        this.searchString = '';

        this.reviewScore = 0;

        this.today = new Date().getDay();

        this.vendorDataService.currentVendor = data;

        //load marker onto map
        $rootScope.$broadcast(event.ui.vendor.pageLoad, data);

        //get menu
        vendorDataService.getVendorMenu(data._id)
            .then((res)=> {
                this.data.menu = res.menu;
                this.menuContainer = this.data.menu;
                this.totalResults = this.getTotalResults();
                this.availableMenuCategories = this.getAvailableMenuCategories();
            })
            .catch(() => {
                this.toastr.error('Whoops, Something went wrong! We were not able to load the menu.',  'Error');
            });
    }

    //get todays hours
    getTodaysHours() {
        let today = this.data.hours[new Date().getDay()];
        return (today.opening_time || '9:00am') + ' - ' + (today.closing_time || '5:00pm');
    }  
}

When I tried to log vm.data I'm getting 当我尝试记录vm.data时

Error: [$injector:unpr] Unknown provider: dataProvider <- data <- VendorController 错误:[$ injector:unpr]未知提供程序:dataProvider <-数据<-VendorController

TypeError: undefined is not an object (evaluating 'vm.data') TypeError:undefined不是对象(正在评估“ vm.data”)

Mocking JSON data should work with $provide constant , after the mocking of your module. 在对模块进行模拟之后,模拟JSON数据应与$ provide常量一起使用。

let data = {"_id":"56b54f9368e685ca04aa0b87",
"lat_lon":"33.713018,-117.841101",...}

beforeEach(angular.mock.module('thcmaps-ui',
($provide) => {
    $provide.constant('data', new data);
  }));

To be honest I just tried it out with functions, not with JSON data, but it should work the same way. 老实说,我只是使用函数而非JSON数据进行了尝试,但是它应该以相同的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM