javascript - 导出代码块而不仅仅是函数
问题描述
目前在我的代码中,VehicleFactory
我想进行单元测试。和VehicleFactory
'sprototype
在函数声明后赋值:
export function VehicleFactory() {
}
VehicleFactory.prototype.vehicleClass = Car;
VehicleFactory.prototype.createNewVehicle = function(options) {
if( options.vehicleType === 'Car') {
this.vehicleClass = Car;
}
else if( options.vehicleType === 'Truck') {
this.vehicleClass = Truck;
}
return new this.vehicleClass(options);
}
var factory = new VehicleFactory();
var car = factory.createNewVehicle( {
vehicleType: "car",
color: "yellow",
doors: 6 } );
function Car(options) {
if( options.brand != undefined)
this.brand = options.brand;
else
this.brand = "Jeep";
if( options.color != undefined)
this.color = options.color;
else
this.color = "White";
}
function Truck(options) {
/// ...
}
console.log(car);
在我的玩笑中:
import VehicleFactory from '../VehicleFactory'
test('vehicleFactory_withCarOptions_AlwaysReturnsCar', () => {
var factory = new VehicleFactory();
var car = factory.createNewVehicle( {
vehicleType: "car",
color: "yellow",
doors: 6 } );
expect(car).toEqual({color: "yellow",
doors: 6});
});
错误显示:
TypeError: _VehicleFactory.default is not a constructor
20 |
21 | test('vehicleFactory_withCarOptions_AlwaysReturnsCar', () => {
> 22 | var factory = new VehicleFactory();
| ^
23 | var car = factory.createNewVehicle( {
24 | vehicleType: "car",
25 | color: "yellow",
我的猜测是export
只导出空函数而不是下面的原型分配?如何解决?
解决方案
问题是我忘记了括号import
而不是import VehicleFactory from '../VehicleFactory'
,
它应该是import {VehicleFactory} from '../VehicleFactory'
对于命名导出,我应该使用括号,
对于默认导出,我不需要括号,因为一个模块只有一个默认导出。
推荐阅读
- python - 连接字典中元组的三元组
- android - 后台服务中的 Google Vision API?
- python - 如何让 Spyder 在相关输出上显示?
- image - 从 2D 图像后端创建 3D 游览
- python - Google Cloud IoT 核心 JWT 过期居然是 24 小时?
- arrays - 嵌套对象中的 Logstash 嵌套对象
- acumos - Acumos 安装和 /var/lib/docker 大小
- gcc - version-script 可以只提供没有默认值的版本化符号吗?
- git - 我对分支中的本地文件进行了更改并进行了提交,但没有推送到原点。怎样才能找回原来的文件?
- video - 如何在颤动中将视频文件上传到服务器