gpt4 book ai didi

javascript - 单元测试 Jasmine 中的 Angular 服务方法

转载 作者:行者123 更新时间:2023-11-30 09:58:38 25 4
gpt4 key购买 nike

我有一个简单的 Angular 服务,它调用一个方法 (this.updateVariable),解析收到的值,并用一个字符串更新一个变量 (myString)。

我想了解如何编写单元测试来测试接收到的值是否正在使用正确的字符串更新变量。

服务:

app.service('myService', function() {

this.updateVariable = function (status, data) {

var myString = '';

if (status.toString()[0] == 4 && data.message !== undefined) {

if ((data.message.indexOf("Out of spoons") > -1) || (data.message.indexOf("Out of forks")) > -1){
myString = "Sorry, weve ran out of spoons and/or forks";
}
else if (data.message.indexOf("Out of plates") > -1) {
myString = "Sorry, weve ran out of plates";
}
else {
myString = "We seem to be facing a technical issue";
}
}

if (status.toString()[0] == 9) {
myString = "Ooops, looks like something is broke.";
}

return myString;
};
});

最佳答案

您的服务测试可能如下所示:

describe('myService Tests', function () {
beforeEach(module('myApp'));

beforeEach(inject(function (_myService_) {
this.sut = _myService_;
}));

describe('when status 400', function () {
beforeEach(function () {
this.status = 400;
});

describe('and no message', function () {
it('should return empty string', function () {
//arrange
var data = {};

//act
var result = this.sut.updateVariable(this.status, data);

//assert
expect(result).toBe("");
});
});

describe('and out of spoons message', function () {
it('should return out of spoons/forks string', function () {
//arrange
var data = {
message: "Out of spoons"
};

//act
var result = this.sut.updateVariable(this.status, data);

//assert
expect(result).toBe("Sorry, weve ran out of spoons and/or forks");
});
});

describe('and out of plates message', function () {
it('should return out of plates string', function () {
//arrange
var data = {
message: "Out of plates"
};

//act
var result = this.sut.updateVariable(this.status, data);

//assert
expect(result).toBe("Sorry, weve ran out of plates");
});
});

describe('and no spoons or plates message', function () {
it('should return technical issue string', function () {
//arrange
var data = {
message: "Some other message"
};

//act
var result = this.sut.updateVariable(this.status, data);

//assert
expect(result).toBe("We seem to be facing a technical issue");
});
});
});

describe('when status 900', function () {
beforeEach(function () {
this.status = 900;
});

it('should return something broke string', function () {
//arrange
var data = {};

//act
var result = this.sut.updateVariable(this.status, data);

//assert
expect(result).toBe("Ooops, looks like something is broke.");
});
});

});

关于javascript - 单元测试 Jasmine 中的 Angular 服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32734599/

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