如何使用resharper testr jasmin测试spa js模块?

时间:2013-08-14 14:37:22

标签: javascript unit-testing requirejs resharper

在VS中阅读了关于javascript单元测试/ bdd之后我发现你可以使用以下组合:

- ReSharper - support for PhantomJS headless + Jasmine/QUnit
- Testr - mock Require dependencies

我在测试脚本中使用了Jasmine,并且能够成功运行一些简单的测试,并在同一个文件中声明了函数。

但是,我无法找到/构建一个工作端到端的示例来测试具有依赖关系的js模块。我试图建立在John Papa的SPA Jumpstart示例中使用的示例。

因此给出了一个在datacontext.js中具有依赖关系的people.js viewmodel模块:

define(['services/datacontext'],
 function (datacontext) {
var peopleViewModel = {        
                       title: 'People page'
                      };
return peopleViewModel;
})

文件夹结构:

/App/Viewmodels : people.js
/App/Services : datacontext.js
/App/Tests : peopletests.js

我需要在peopletests.js中添加什么才能运行此测试?

describe("My Tests Set", function () {
 it("People Title Test", function () {
   expect(peopleViewModel.title()).toEqual("People page");
 });
});

1 个答案:

答案 0 :(得分:1)

试试这个:

  1. 将require.js添加为参考路径
  2. 添加require.config脚本作为参考路径
  3. load require modules。
  4. peopletests.js:

    /// <reference path="~/Scripts/require.js"/>
    /// <reference path="~/App/requireConfig.js"/>
    
    describe("My Tests Set", function () {
    var people;
    
    beforeEach(function () {
        if (!people) { //if people is undefined it will try to load it
           require(["people"], function (peopleViewModel) {
                people = peopleViewModel;
            });
            //waits for people to be defined (loaded)
            waitsFor(function () { 
                return people;
            }, "loading external module", 1000);
        }
    });
    
     it("People Title Test", function () {
       expect(people.title).toEqual("People page");
     });
    });
    

    requireConfig.js:

    //beware of the port, if your app is runing in port 8080 
    //you need to specified that to require since resharper whould use a random port 
    //when running tests 
    require.config({
        baseUrl: 'http://localhost:8080/App/',
        paths: {
            people: 'ViewModels/people',
            dataContext: 'Services/datacontext'
        }
    });
    

    people.js

    define(['dataContext'],
     function (datacontext) {
    var peopleViewModel = {        
                           title: 'People page'
                          };
    return peopleViewModel;
    })