简体   繁体   English

单元测试以获取角度4中的随机数

[英]Unit testing for getting random Number in angular 4

I have a method in my ts file to create random list as below. 我的ts文件中有一个创建随机列表的方法,如下所示。

list = [];

createItem(index, random_boolean) {
    return { id: index, name: `Item ${index}`, details: `Item ${index} occured`, selected : random_boolean };
}
createRandomItem() {
    const int = parseInt((Math.random() * 100) + '', 10);
    const random_boolean  = Math.random() >= 0.5;
    return this.createItem(int, random_boolean);
  } 

for (var i = 0; i < 10; i++) {
    list.push(this.createRandomItem(i));
}

How to write unit test case for createRandomItem() method. 如何为createRandomItem()方法编写单元测试用例。

Thanks for the help. 谢谢您的帮助。

You need to decide what specifically you are trying to test. 你需要决定你想考什么特别 You can probably trust that Math.random() has been tested and works as advertised, so you don't need to test that. 您可能可以相信Math.random()已经过测试,并且可以像宣传的那样工作,因此您无需进行测试。 After that, what are you left with? 之后,您还剩下什么? You can test that given two random numbers, your method does the right thing with them. 您可以测试给定的两个随机数,您的方法会对它们执行正确的操作。 To do that, you can mock Math.random() so it delivers predictable results and then assert the the returned object has the expected properties. 为此,您可以模拟Math.random()以便它提供可预测的结果,然后断言返回的对象具有预期的属性。 If you are using Jasmine, it might look something like: 如果您使用的是Jasmine,它可能类似于:

it("should return an object based on the result of Math.random()", function() {
    spyOn(Math, 'random').and.returnValues(0.1, 0.75);
    let t = obj.createRandomItem()
    expect(t).toEqual({ 
        id: 10,
        name: 'Item 10',
        details: 'Item 10 occured',
        selected: true }); 
});

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

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