问题描述
我想知道是否有一种方法可以正确测试Angular中函数的返回值.我想本质上测试一个测试的返回值为true,然后编写另一个测试相反的场景.
I am wondering if there is a way to correctly test the return value of a function in Angular. I want to essentially test the return value to be true for one test and write another to test the opposite scenario.
Ts组件:
get() {
if (this.object == undefined) {
return true;
} else {
return false;
}
}
我现在认为适合测试返回值的唯一方法是设置一个变量来保存返回值.以下是我的尝试,我只是坚持要说的是预期的.
The only way I can see fit right now to test the return value is to set a variable to hold the return value. Below is my attempt, I'm just stuck on asserting what is to be expected.
测试:
it('should call get function and return true', () => {
//Arrange
component.object = undefined;
//Act
component.get();
//Assert
expect(component.get). <-- *stuck here*
});
推荐答案
在 act 中获取值,然后在 assert 中将其检查为true
.
Get the value in the act and then check it to be true
in the assert.
it('should call get function and return true', () => {
// Arrange
component.object = undefined;
// Act
var result = component.get();
// Assert
expect(result).toBe(true);
});
请注意,方法get
的主体可以简化为
On a side note the body of the method get
could be simplified to just
return this.object === undefined;
这篇关于如何对函数的返回值进行单元测试-Angular(Jasmine/Karma)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!