简体   繁体   English

无法在笑话中测试rsvp许诺

[英]Unable to test rsvp promises in jest

I'm stuck with writing unit tests for my code that uses rsvp promises. 我一直在为使用rsvp promises的代码编写单元测试。 I tried to use pit tests but had no luck in making tests pass for rsvp, however embedded promises work just fine: 我尝试使用pit测试,但没有通过rsvp的测试,但运气不佳,但是嵌入式的承诺工作得很好:

//jest.autoMockOff(); - even with this rsvp test is failing
jest.unmock('rsvp');

import rsvp from 'rsvp';

describe('my rsvp tests', () => {

  // this test fails
  pit('testing rsvp promise', () => {
    return new rsvp.Promise((resolve) => {
      resolve("getting something");
    }).then(()=> { expect(1).toBe(1); });
  });

  // this test passes
  pit('testing pure promise', () => {
    return new Promise((resolve) => {
      resolve("getting something");
    }).then(()=> { expect(1).toBe(1); });
  });
});

Relevant details from my package.json: 来自我的package.json的相关详细信息:

"rsvp": "^3.2.1",
"babelify": "^7.2.0",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"babel-jest": "^9.0.0",
"jest-cli": "*"
 ...
"scripts": {
  "test": "jest"
},

"jest": {
  "unmockedModulePathPatterns": [
    "<rootDir>/node_modules/react",
    "<rootDir>/node_modules/react-dom",
    "<rootDir>/node_modules/react-addons-test-utils"
  ]
}

.babelrc: .babelrc:

{
  "presets": ["es2015", "react", "stage-0"]
}

I see two possible workarounds but like none of them: 我看到了两种可能的解决方法,但都不是:

  1. Mock rsvp promise by using embedded promise. 通过使用嵌入式Promise模拟rsvp Promise。 Disadvantage: unit tests will become more verbose, I'll need to mock another functions such as rsvp.all that I don't want to do. 缺点:单元测试将变得更加冗长,我需要模拟另一个我不想做的功能,例如rsvp.all。
  2. Migrate from rsvp to embedded promises. 从rsvp迁移到嵌入式Promise。 It is possible, however I already use one library that depends on rsvp that makes ajax requests. 有可能,但是我已经使用了一个库,该库依赖于发出ajax请求的rsvp。 I'm also not sure that embedded promises can replace everything that rsvp provides (such as 'all' and the other helper functions). 我也不确定嵌入式Promise是否可以替代rsvp提供的所有内容(例如“ all”和其他辅助函数)。

I found a solution - or, better say, a workaround. 我找到了一个解决方案-或者更好的解决方法。 In short: there is no need to use pit methods, they can be replaced with 'it', but before completion all timers should be run, it can be done by calling jest.runAllTimers(). 简而言之:不需要使用pit方法,可以将它们替换为“ it”,但是在完成所有计时器之前,可以通过调用jest.runAllTimers()来完成。

It is not an elegant solution as I don't see any reason why rsvp promises shouldn't work in jest as opposed to 'embedded' ones, but at least it works. 这不是一个优雅的解决方案,因为我看不出rsvp承诺不应该与“嵌入式”承诺开玩笑的任何理由,但至少可以奏效。

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

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