简体   繁体   English

Angular2 +-作为变量传递时找不到模块-测试

[英]Angular2+ - Cannot find module when passed as variable - testing

In my test I am requiring a .json file with data that I will check against. 在测试中,我需要一个.json文件,其中包含要检查的数据。 However, I cannot seem to pass the string of where to find it into the require... 但是,我似乎无法将在哪里找到它的字符串传递到require中。

Working code 工作代码

const data = require('../../../assets/data.json');

Does not work 不起作用

const jsonUrl = '../../../assets/data.json';
const data = require(jsonUrl);

I am wanting to use the variable jsonUrl as this url string is to be used a few times within the test itself. 我想使用变量jsonUrl因为此url字符串将在测试本身中使用几次。 I just don't understand why it cannot find it? 我只是不明白为什么找不到它?


Amendment to question: 修正问题:

Since mocking is the way to go on this, and I am unsure of exactly how to do this... I am amending the question to help with this. 由于嘲笑是进行此操作的方式,因此我不确定该如何执行...我正在修改问题以帮助解决此问题。

From what I am thinking with testing, I assume that I need to read in the data I am actually using and then test with that. 根据我对测试的考虑,我假设我需要读入我实际使用的数据,然后进行测试。 If I am wrong then please correct me. 如果我错了,请纠正我。

Here is what I am testing... 这是我正在测试的...

data.json data.json

[
  {
    "name": "one",
    "id": 1,
  },
  ...
  // This format is used for approx 20 entries
]

component.ts component.ts

ngOnInit() {
   loadData().subscribe(data => {
       this.data = data;
    };
}

loadData() {
   const statusUrl = '../../../assets/data.json';
   return this.httpClient.get(statusUrl);
}

test.ts Receiving cannot find module because of require issue stated above. 由于上述要求问题, test.ts接收方找不到模块。

it('should load status data from local json', fakeAsync(() => {
    const jsonUrl = '../../../assets/status.json';
    const data = require(jsonUrl);
    const request = httpMock.expectOne(jsonUrl);
    request.flush(data);
    expect(component.status).toEqual(data);
  }));

This was solved by making it equal any kind of object: 通过使它等于任何种类的对象来解决:

it('should load status data from local json', fakeAsync(() => {
    const jsonUrl = '../../../assets/greyhound.status.json';
    const data = [];

    const request = httpMock.expectOne(jsonUrl);
    request.flush(data);
    expect(component.raceStatuses).toEqual(data);
  }));

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

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