[英]Mock ES6 dependencies when unit testing
Assume the following two ES6 classes: 假定以下两个ES6类:
my-random.js: my-random.js:
export default class MyRandom {
get() { return Math.random(); }
}
app.js: app.js:
import MyRandom from './random';
export default class App {
get() {
let r = new MyRandom();
let total = r.get() * r.get(); // Complex calc goes here!
return total;
}
}
Now I would like to unit test the get
from app.js
. 现在,我想对来自
app.js
的get
进行单元测试。 So I would like to mock MyRandom
. 所以我想嘲笑
MyRandom
。 Todo this I found a very interesting library Mocktail 为此,我发现了一个非常有趣的库Mocktail
According to the docs you should change my-random.js to 根据文档,您应该将my-random.js更改为
import {mock} from 'mocktail';
class MyRandom {
get() { return Math.random(); }
}
export default mock(MyRandom);
In your test file you have to tell the environment that you're testing as follows: 在测试文件中,您必须按照以下步骤告诉环境您正在测试:
import {env, ENV, inject} from 'mocktail';
env(ENV.TESTING);
class MyRandomMock {
get() {
return 10; // Not so random anymore
}
}
inject('MyRandom', MyRandomMock);
And you should be able to test app.js
. 并且您应该能够测试
app.js
Unfortunately when I try this MyRandom is never replaced with the mock class. 不幸的是,当我尝试使用MyRandom时,它永远不会被模拟类所替代。 Any help would be appreciated!!
任何帮助,将不胜感激!!
I've setup a test project on github here to demonstrate the issue. 我在这里的 github上设置了一个测试项目来演示该问题。 As you can see the tests will fail :(
如您所见,测试将失败:(
If there are better ways to achieve what I need please tell me! 如果有更好的方法来实现我所需要的,请告诉我!
I think you need to import setup
before App
in your test file, this will inject mock and make it called in App. 我认为您需要在测试文件中的
App
之前导入setup
,这将注入模拟并在App中调用它。
import './setup';
import App from '../src/app';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.