简体   繁体   English

如何在函数内部调用的Karma单元测试中模拟Promise

[英]How to mock a promise in Karma unit test called inside a function

I have the following function in my Angular controller and want to test, if the promise returns the expected result 我的Angular控制器中具有以下功能,并且要测试一下,如果promise返回了预期的结果

    function getName() {
      var name = "";
      nameService.getName().then(function (data) {
        name = data.name;
      });
      return name;
    }

How can I mock the promise call with fake data? 如何用虚假数据模拟Promise调用? I am not sure if I can use $httpBackend or $provide here? 我不确定是否可以在此处使用$ httpBackend或$ provide? I tried this but it didn't work: 我试过了,但是没有用:

it("function getName should get the name from the nameService.getNameInfo function", function () {
        var name = { name: "name1"};
        spyOn(mockNameService, 'getNameInfo').and.callFake(function() {
            return {
                then: function(callback) {return callback(name);}
            };
        });
        var result = myCtrl.getName();
        expect(result).toEqual("name1");
    });

Try using: 尝试使用:

spyOn(mockNameService, 'getNameInfo').and.returns($q.when('dummyData'));

to mock your data. 模拟您的数据。 Then you need to verify once it is resolved. 然后,您需要在解决后进行验证。 So write: 所以写:

expect(myCtrl.getName().then(function(name){
    expect(name).toBe('dummyData');
}).toBeResolved();

The problem is not with your unit testing code, its an wrong implementation at all of the application code. 问题不在于您的单元测试代码,而是所有应用程序代码的错误实现。 here: 这里:

function getName() {
      var name = "";
      nameService.getName().then(function (data) {
        name = data.name;
      });
      return name; //it will return "" because the promise yet not resolved
    }

In this code function getName will always return a empty string "" and it will never return the values you are assigning when the promise resolves name = data.name because promises are asynchronous, so by the time its resolves the function getName already returned the empty string to the caller! 在此代码函数中, getName将始终返回一个空字符串""并且当name = data.name解析name = data.name时,它绝不会返回您所分配的值,因为Promise是异步的,因此在其解析函数getName时,它已经返回了空值串给来电者! So, in this case, refactoring the original code and fixed it there dhould be the first idea! 因此,在这种情况下,重构原始代码并进行修复应该是第一个想法!

Actually your unit test codes identified the bug in your code, so its served already its original purpose, test case failing doesn't always meant that you have to fix it there, rather if your test cases are perfectly written against the logical expectation for all possible units/modules you need to think about why it is failing, looking at the actual code, and that is the actual purpose of writing unit test cases 实际上,您的单元测试代码已识别出代码中的错误,因此它已达到了其最初的目的,测试用例失败并不总是意味着您必须在此进行修复,而是如果您的测试用例是针对所有对象的逻辑期望而完美编写的您需要考虑可能的单元/模块失败的原因,查看实际的代码,这就是编写单元测试用例的实际目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM