我有一个 Controller ,为简洁起见进行了简化:
.controller('myCtrl', ['$scope', 'data', function ($scope, data) {
$scope.myVar = testFunction(data.name);
function testFunction (name) { ... }; //returns string or null
};
data
是我使用 stateProvider 中 state
的 resolve
属性获得的对象。
我想要两个 Jasmine 测试来验证 $scope.myVar
是:
- 当
data.name
有值时,某种字符串(并不重要)。 - 如果
data.name
没有值,则为 null。
例如:
it('should verify myVar is null when name has no value', function () {
expect(scope.myVar).toBeNull();
});
我的问题是 it('test title', function () {..});
规范在 beforeEach
函数中初始化 Controller 之后运行。因此,如果我想设置 data
,我需要在 beforeEach
部分中进行。但如果我这样做,我会提前确定 name
,而我希望它在我的两次测试中都不同 - 例如一次为 null,一次为“John”。
当一个人想要设置将在 Controller 初始化中使用的对象并使用不同的值测试它们时,最佳实践是什么?
(注意:由于我不想污染作用域,该函数是私有(private)的。)
最佳答案
作为最初的预感,我很可能会在两个单独的 describe
部分中对其进行测试:
describe('null title', function () {
beforeEach(function () {
// setup so that resolve returns null
});
it('verify null', function () {
// the test
});
});
describe('not null title', function () {
beforeEach(function () {
// setup so that resolve returns not null
});
it('verify not null', function () {
// the test
});
});
这对您来说可行吗?
关于javascript - 如何测试依赖于注入(inject)数据的范围变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055322/