【发布时间】:2018-04-08 11:32:37
【问题描述】:
代码示例
这可能在代码中得到更好的解释,所以我在下面包含了一个详细的抽象示例 - 我的问题在 cmets 中重复了。
示例摘要
例如,您模拟了一个相当复杂的模拟服务,并且在第一个测试中,您希望模拟服务对一个函数给出肯定的结果(在下面的示例中返回代码 200)。在第二个测试中,您希望相同的函数返回否定结果,例如 500。
我发现我可以简单地注入提供程序并覆盖方法,但这是正确的方法吗?请参阅下面的“测试 2”。
describe('CommentArea', function() {
var controller
beforeEach(function() {
module('app', function($provide) {
// Base mock definition
$provide.provider('comments', function() {
this.$get = function() {
return {
create: function() {
return new Promise(function(resolve) {
resolve({ code: 200 })
})
},
delete: function() {
return new Promise(function(resolve) {
resolve({ code: 200 })
})
}
}
}
})
})
inject(function($componentController) {
controller = $componentController('CommentArea')
})
})
// Start tests
//
// Test 1 - Use the above mocked service "as is" - happy path scenario
//
it('appends comment when successful', function() {
expect(controller.commentCount).toEqual(0)
controller.create() // uses the comments service create method
expect(controller.commentCount).toEqual(1)
})
// Test 2 - Use the above mocked service with a slight modification
// This time the create function will fail
//
it('does not append comment when unsuccessful', inject(function(comments) {
// overwrite for failure condition here
// QUESTION - is this acceptable? It seems odd just overwriting it
// so directly
comments.create = function () {
return new Promise(function(resolve) {
resolve({ code: 500 })
})
}
expect(controller.commentCount).toEqual(0)
controller.create() // uses the comments service create method
expect(controller.commentCount).toEqual(0)
}))
})
【问题讨论】:
标签: javascript angularjs unit-testing angular-services