繁体   English   中英

从 Promise 获取值进行单元测试

[英]get value from a Promise for unit-testing

我在 class 中有一个方法计算返回 Promise 的 2 个参数的总和(必须):

module.exports = class Sum {
  sum(a, b) {
    let c = a + b;
    const myPromise = new Promise(function(myResolve) {
      setTimeout(function(){ myResolve(c); }, 100);
    });
    return myPromise;
  }
}

我使用 Jasmine 框架进行单元测试

const MyLocalVariable1 = require('../src/sum'); 
describe('CommonJS modules', () => {
  it('should import whole module using module.exports = sum;', async () => {
    const result = new MyLocalVariable1();
    expect(result.sum(4, 5).then(function(value) {
      return value;
    })).toBe(9);
  });
}

第一个表达式是我们要测试的:

result.sum(4, 5).then(function(value) {
  return value;
})

第二个是期望值:

toBe(9)

但是我怎样才能从第一个表达式中得到一个值,因为它是一个 Promise,它的预期值为[object Promise] 提前致谢

要将 Konrad 的观点带回家,您可以执行以下操作:

it('should import whole module using module.exports = sum;', async () => {
    const result = new MyLocalVariable1();
    const answer = await result.sum(4, 5);
    expect(answer).toBe(9);
  });

或以下内容:

// add done callback to tell Jasmine when you're done with the unit test
it('should import whole module using module.exports = sum;', (done) => {
    const result = new MyLocalVariable1();
    result.sum(4, 5).then(answer => {
      expect(answer).toBe(9);
      done();
   });

  });

暂无
暂无

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

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