单元测试和嘲笑承诺中的方法

时间:2017-10-20 22:53:39

标签: node.js unit-testing promise jasmine

如果有一个逻辑要用各种顺序承诺进行单元测试,那么如何在then(() => {})函数内对逻辑进行实际断言呢?通过类似于下面的设置,我遇到第一个测试将通过但第二个测试没有通过的问题。我很好奇为什么匿名然后在实现中的块永远不会到达。

//Implementation
class FiddleService {
    constructor(dependencies = {}) {
        const { someService = new SomeService() } = dependencies;
        this.someService = someService;
    }

    doSomething(params) {
        this.someService.asyncOperation1(params).then((result) => {
            ...
            //never gets called by spy in test
            return this.someService.asyncOperation2(result.firstName);
        }).then((result) => {
            return this.someService.asyncOperation3(result.age);
        });
    }
}
//test
describe("FiddleService", () => {
    let someService;
    beforeAll(() => {
        someService = new SomeService();
        spyOn(someService.asyncOperation1).and
          .returnValue(new Promise(() => {firstName: "Jan"});
        spyOn(someService.asyncOperation2).and
          .returnValue(new Promise(() => {age: 50});
        spyOn(someService.asyncOperation3);
    });

    it("calls asyncOperation1", () => {
        let fiddleService = new FiddleService();
        fiddleService.doSomething({});
        expect(someService.asyncOperation1).toHaveBeenCalled();
    });

    it("calls asyncOperation2", () => {
        let fiddleService = new FiddleService();
        fiddleService.doSomething({});
        expect(someService.asyncOperation2).toHaveBeenCalled();
    });
});

2 个答案:

答案 0 :(得分:0)

@ roamer-1888表示解决方案与调用promises并在测试中调用完成有关。

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="CommonServiceLocator" version="1.3" targetFramework="net461" />
  <package id="Prism.Core" version="6.3.0" targetFramework="net461" />
  <package id="Prism.Mef" version="6.3.0" targetFramework="net461" />
  <package id="Prism.Wpf" version="6.3.0" targetFramework="net461" />
</packages>

答案 1 :(得分:0)

Jasmine不是我技能组合的主要部分所以暂时提供。

我仍然认为你需要Promise.resolve()而不是new Promise()两个地方,并认为你可以利用Jasmine的能力在一次测试中处理多个expect(),而不会丢失信息。

//test
describe("FiddleService", () => {
    let someService;
    beforeAll(() => {
        someService = new SomeService();
        spyOn(someService.asyncOperation1).and.returnValue(Promise.resolve({firstName: "Jan"}));
        spyOn(someService.asyncOperation2).and.returnValue(Promise.resolve({age: 50}));
        spyOn(someService.asyncOperation3);
    });

    it("should make three sequential async calls", (done) => {
        let fiddleService = new FiddleService();
        fiddleService.doSomething({}).then(_ => {
            expect(someService.asyncOperation1).toHaveBeenCalled();
            expect(someService.asyncOperation2).toHaveBeenCalled();
            expect(someService.asyncOperation3).toHaveBeenCalled();
            done();
        });
    });
});