gpt4 book ai didi

javascript - 尝试为每一行编写测试用例

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:49 25 4
gpt4 key购买 nike

  • 编写了跳跃方法的测试用例,
  • 但当我看到代码覆盖率报告时,它并没有进入 onloadend 方法 seat.onloadend。
    • 在 createSpyObj 中我调用了 loadend 但它仍然没有进入内部
  • 你们能告诉我如何解决吗?
  • 在下面提供我的代码和测试用例。
  • 我正在尝试为每一行编写测试用例。
  jumping(inputValue: any): void {
var that = this;
var file: File = inputValue.files[0];

var seat: FileReader = new FileReader();
seat.onloadend = (e) => {
this.encodeBase64 = seat.result;
that.fileSelect = $("#laptop").val().replace(/^.*\\/, "");
if (that.fileSelect == '') {
that.dragDrop = that.swimming;
} else {
that.dragDrop = "";
that.dragDrop = that.fileSelect;
}
}
$('.running').show();
if (inputValue.files.length > 0) {
var wholeQuantity = 0;

wholeQuantity = inputValue.files[0].size / 1048576; //size in mb

if (wholeQuantity > 5) {
$('.stars').show();
$("#laptop").val('');
this.fileSelect = "";
}

seat.readAsDataURL(file);
}
}






describe('Jasmine Unit Tests: hand-Basketball-Manage-mobiles', () => {
let rainSPORTSService:SPORTSService;
let SPORTSService: SPORTSService;
let decodeService: DecodeService;
let BasketballChainComponent: handBasketballChain;
let kickViewrainsComponent: kickViewrains;
let tiger: Componenttiger<handBasketballChain>;
let raintiger: Componenttiger<kickViewrains>;
let foodktiger: Componenttiger<foodkCarousel>;
let kendotiger: Componenttiger<KendoGridComponent>;
let foodkComponent:foodkCarousel;
let kendoComponent:KendoGridComponent;
beforeEach(async(() => {

jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

TestBed.configureTestingModule({
imports: [HttpModule, FormsModule,BrowserModule ],
declarations:[handBasketballChain, KendoGridComponent,ProgressCircle,
kickViewrains,handLeftSliderComponent,foodkCarousel,kickmobiles],
providers:[SPORTSService,DecodeService,recentPinnedHistoryService,
{provide: Router, useClass: RouterModule}, validationService,saveService,
ChainService]
}).compileComponents().then(() =>{
foodktiger = TestBed.createComponent(foodkCarousel);
kendotiger = TestBed.createComponent(KendoGridComponent);
foodkComponent = foodktiger.componentInstance;
kendoComponent = kendotiger.componentInstance;
tiger = TestBed.createComponent(handBasketballChain);
BasketballChainComponent = tiger.componentInstance;
SPORTSService = tiger.debugElement.injector.get(SPORTSService);
tiger.componentInstance.kickmobiles.SPORTSService=tiger.debugElement.injector.get(SPORTSService);
tiger.componentInstance.kickViewrains.SPORTSService=tiger.debugElement.injector.get(SPORTSService);
decodeService = tiger.debugElement.injector.get(DecodeService);
BasketballChainComponent.inputfoodkCarousel = foodkComponent; //jasmine.createSpy('foodkCarousel');//.andCallFake(function(msg) { return this });
BasketballChainComponent.kickmobiles.gridkendo=kendoComponent;
})}
));



it('Read kick mobile', (done) => {


let callFirstTime : boolean = true;
let url=

spyOn(BasketballChainComponent.kickmobiles.SPORTSService,'getResponse').and.
callFake(() => {
if(callFirstTime) {
callFirstTime = false; // Invoked by detectChanges()
return Observable.of([{
"mobileId": "100",
"mobileName": "http://localhost:3000/assets/js/actualairings.json",
"mobileType": "TITLE",
"mobileData": "YWZjYXJlZ2Vyamh2dmFyZWdoYnZi",
"notes": "",
"notesId": "100",
"elfDocID": "100",
"url": "http://localhost:3000/upload",
"date": "06/27/2017",
"addedByName": "Kamal",
"userID": "206509786",
"operationType": "create"
}]);
}
});


const fileReaderSpy = jasmine.createSpyObj('FileReader', ['readAsDataURL', 'onloadend']);
spyOn(window, 'FileReader').and.returnValue(fileReaderSpy);

BasketballChainComponent.kickmobiles.jumping({
files: "Untitled-2.txt"
});

var seat = new FileReader();

//seat.onloadend(e);

//BasketballChainComponent.kickmobiles.jumping.onloadend()


tiger.whenStable().then(() => {
done();
});
});
});

最佳答案

请记住,单元测试的关键是编写小的可测试代码单元。 Unit Testing - Wikipedia

在大多数情况下,您都在正确的轨道上,在调用“跳跃”函数之前 stub FileReader 等等。这是测试依赖于另一个外部库/函数/框架的代码的方法。单元测试状态的维基百科页面的相关部分

Because some classes may have references to other classes, testing a class can frequently spill over into testing another class. A common example of this is classes that depend on a database: in order to test the class, the tester often writes code that interacts with the database. This is a mistake, because a unit test should usually not go outside of its own class boundary, and especially should not cross such process/network boundaries because this can introduce unacceptable performance problems to the unit test-suite.

但事情是这样的,当您创建虚拟 FileReader 或模拟时,它永远不会调用“onloadend”,因为模拟/ stub 没有实现该事件和事件系统。这意味着您的模拟不完整。维基百科指出

Instead, the software developer should create an abstract interface around the database queries, and then implement that interface with their own mock object. By abstracting this necessary attachment from the code (temporarily reducing the net effective coupling)

在您的情况下,您将模拟 FileReader loadend 事件,而不是数据库。

从测试的 Angular 来看,您当前的代码需要一个小的重构才能变得可测试。单元测试的总体目标是单独测试小的功能单元。

The objective in unit testing is to isolate a unit and validate its correctness.

“跳跃”函数依赖于附加到 onloadend 的嵌套箭头函数。您的代码直接调用了测试中注释掉的代码,老实说,这并没有提高您的代码覆盖率,我有点惊讶,建议您确保您的代码覆盖率工具,如果您是,可能是 Istanbul 尔使用 Jasmine 已正确配置。

除此之外,您应该重构该嵌套函数,而是创建一个命名函数,然后您可以直接调用该函数进行单元测试。

这是一个(在我这边未经测试的)示例,它是实现您的功能的更好方法。

jumping(inputValue: any): void {
var that = this;
var file: File = inputValue.files[0];

var seat: FileReader = new FileReader();
// bind the arguments for the event handler, first arg will be 'this' of the
// loaded named function
// second is 'that' variable, seat is seat and the final 'e' variable is
// implicit and shouldn't be specified.
seat.onloadend = loaded.bind(seat, that, seat);

$('.running').show();
if (inputValue.files.length > 0) {
var wholeQuantity = 0;

wholeQuantity = inputValue.files[0].size / 1048576; //size in mb

if (wholeQuantity > 5) {
$('.stars').show();
$("#laptop").val('');
this.fileSelect = "";
}

seat.readAsDataURL(file);
}
}

loaded(that: any, seat: any, e: any): void { // now a testable named function
this.encodeBase64 = seat.result;
that.fileSelect = $("#laptop").val().replace(/^.*\\/, "");
if (that.fileSelect == '') {
that.dragDrop = that.swimming;
} else {
that.dragDrop = "";
that.dragDrop = that.fileSelect;
}
}

一个测试示例将覆盖上面编写的“已加载”函数的所有代码行,如下所示:

describe('test suite', function () {
var old$ = $;

afterEach(function () {
$ = old$;
});

it('covers all lines and else path on if but does not actually test anything', function () {
$ = function () {
val: function () {
return 'Untitled-2.txt';
}
}; // stub JQuery

var seat = {
result: 'Base64encoded'
};
var scope = {};
var that = {
swimming: false,
dragDrop: null
};

BasketballChainComponent.kickmobiles.loaded.call(scope, that, seat, null);
});

it('covers all lines and on if but not else and does not actually test anything', function () {
$ = function () {
val: function () {
return '';
}
}; // stub JQuery

var seat = {
result: 'Base64encoded'
};

var scope = {};

var that = {
swimming: false,
dragDrop: null
};

BasketballChainComponent.kickmobiles.loaded.call(scope, that, seat, null);
});

});

现在请注意,在现实世界中,您不应该仅仅为了代码覆盖而编写测试,而不会实际测试给定的功能。它会让您产生一种错误的安全感,而不是真正地测试您的代码。 MSDN有这样的话:

The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

你正在做的类比如下:

您是一名汽车碰撞测试员。你的工作是验证汽车在碰撞中是否安全。因此,一辆汽车以 10 公里/小时的速度坠毁,您需要对其进行检查。

您列出了需要确认的事项 list 。因此,在 10 公里/小时的碰撞中,您只希望油漆被划伤。所以你看看油漆,如果油漆被划伤但没有其他损坏,则测试通过。如果汽车凹陷,则测试失败。

总体而言,这是一个很好的测试,因为它测试的是可量化的东西并且测试的是意图。

如果您试图在不实际测试功能的情况下实现 100% 的代码覆盖率,那么您所做的就是撞车,然后不验证任何内容。

你是说“好吧,我撞坏了车,只要我撞对了,我真的不需要检查它在撞车时做了它应该做的事情吗?”。

当然,您通过查看汽车获得了 100% 的碰撞覆盖率,但如果不实际测试它,您可能甚至没有费心。代码覆盖率是发现未经测试的代码的有用工具,它不用于实现获得完整代码覆盖率的任意指标。可以在 Broken promise of 100% code coverage 阅读有关此内容的进一步阅读和出色的文章。

本质上它的症结是

The fact that it is easy to measure code coverage doesn’t make it a good metric though. You can get into trouble even if your code coverage is 100%.

我已经省略了中篇文章中的代码,但是它接着说:

This unit test produces the perfect 100% test coverage for the elementAtIndex: function. Does it prove that the function works correctly? The answer is, obviously, no. What happens when we exceed the array boundaries? Why did that happen? When you try to focus on the code coverage metric you write code that looks at the implementation of the tested function/method. But the implementation is not proven to be correct yet. That is the reason why we want to test it. Even with that simple function code coverage failed as a good metric to measure the quality of unit-tests.

此外,上面我声明您应该测试代码的意图。 Medium 文章也说明了这一点。

What to do instead? Don’t look at the actual implementation of the method, look at the contract instead. Look precisely at the outputs of the function/method for any specific inputs. Look at the side-effects that this function does or uses. Take into account the possible edge cases that might exist. List this information and make tests according to that.

记住100% 的代码覆盖率并不意味着您的代码 100% 正确。

我希望这能帮助您更好地理解单元测试这个概念。

关于javascript - 尝试为每一行编写测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46017512/

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