相关疑难解决方法(0)

如何为angularjs/jasmine单元测试提供可重复使用的样本数据值

我想在我的茉莉花单元测试中提供简单的常量值,如名称,电子邮件等.

这里也提出了类似的问题:AngularJS + Karma:在单元测试指令或控制器时重用模拟服务

在c#中,我将创建一个静态类来保存模拟数据的小片段.然后,我可以在整个单元测试中使用这些值,如下所示:

static class SampleData
{
    public const string Guid = "0e3ae555-9fc7-4b89-9ea4-a8b63097c50a";
    public const string Password = "3Qr}b7_N$yZ6";

    public const string InvalidGuid = "[invalid-guid]";
    public const string InvalidPassword = "[invalid-password]"; 
}
Run Code Online (Sandbox Code Playgroud)

在使用Karma/Jasmine测试我的AngularJS应用程序时,我希望有同样的便利.

我知道我可以constant针对我的角度应用程序定义一个对象,我已经对我在真实代码中使用的常量执行此操作,如下所示:

myApp.constant('config', {apiUrl:'http://localhost:8082'})
Run Code Online (Sandbox Code Playgroud)

我可以像这样添加另一个常量但只包含用于我的单元测试的样本数据值,如下所示:

myApp.constant('sampleData', {email: 'sample@email.com'}) 
Run Code Online (Sandbox Code Playgroud)

然后,我可以将模拟常量对象注入到我的测试中,然后就像这样

describe 'A sample unit test', ->
    beforeEach ->   module 'myApp'
    beforeEach inject ($injector) ->
        @sampleData = $injector.get 'sampleData'
        email = @sampleData.email
        # etc ...
Run Code Online (Sandbox Code Playgroud)

然而这对我来说似乎有点可疑.我不希望我的生产代码包含仅我的单元测试所需的样本数据.

您如何通过可重复使用的样品数据值方便地提供角度/茉莉花单位测试?

谢谢

jasmine angularjs

6
推荐指数
1
解决办法
3391
查看次数

标签 统计

angularjs ×1

jasmine ×1