[英]export code block instead of just function
Currently in my code, I have VehicleFactory
I want to unit test. 当前在我的代码中,我有要进行单元测试的
VehicleFactory
。 And VehicleFactory
's prototype
is assigned after the declaration of the function: 在声明该函数后,会分配
VehicleFactory
的prototype
:
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);
In my jest: 以我的笑话:
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});
});
The error shows: 错误显示:
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",
My guess is export
only exports the empty function but not the following assignment to prototype? 我的猜测是
export
仅导出空函数,而不是以下对原型的赋值? How to fix it? 如何解决?
The problem is I forgot the bracket in import
问题是我忘记了
import
的括号
Instead of import VehicleFactory from '../VehicleFactory'
, 而不是
import VehicleFactory from '../VehicleFactory'
,
it should be import {VehicleFactory} from '../VehicleFactory'
应该
import {VehicleFactory} from '../VehicleFactory'
for named export, I should use bracket, 对于命名出口,我应该使用方括号,
for default export, I don't need bracket, since one module only has one default export. 对于默认导出,我不需要括号,因为一个模块只有一个默认导出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.