gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:02:28 24 4
gpt4 key购买 nike

我的 Controller 中有一个名为 getTodaysHours() 的函数,我想测试它。我想知道是否可以在单元测试规范中模拟下面的 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');
}
}

当我尝试记录vm.data时,我得到了

Error: [$injector:unpr] Unknown provider: dataProvider <- data <- VendorController

TypeError: undefined is not an object (evaluating 'vm.data')

最佳答案

在模拟模块之后,模拟 JSON 数据应该与 $provide 常量 一起使用。

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

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

说实话,我只是用函数尝试了它,而不是用 JSON 数据,但它应该以相同的方式工作。

关于javascript - 如何模拟json数据进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com