简体   繁体   English

Angular 6单元测试静态模拟响应

[英]Angular 6 unit testing static mock response

I am testing an Angular component which calls a service method. 我正在测试一个调用服务方法的Angular组件。 Within the component, I modify some fields of the response before proceeding, like this: 在组件内,我在继续之前修改了响应的某些字段,如下所示:

ngOnInit() {
    this.myService.myMethod(requestData).subscribe(response => {
      response.list.forEach(item => {
        item.someField = someValue;
      })
    });
    ...
}

For testing, I created a mock response like this: 为了进行测试,我创建了一个模拟响应,如下所示:

const mockServiceResponse = {
    list: [],
    ...
}

const myServiceSpy = jasmine.createSpyObj('MyService',['myMethod']);
myServiceSpy .myMethod.and.returnValue( of(mockServiceResponse ) );

The problem is; 问题是; I have several test cases, and ngOnInit is called for each test case. 我有几个测试用例,每个测试用例都调用ngOnInit。 As I modify the service response fields, at each run mockServiceResponse object is modified, and second test case gets the modified version of the response. 当我修改服务响应字段时,每次运行嘲笑服务对象都会被修改,第二个测试用例将获得响应的修改版本。 This is not a problem for the componenet because I actually get a new response each time I call the method, but for testing it causes my test cases to fail. 这对于componenet来说不是问题,因为每次调用该方法时我实际上都会得到一个新的响应,但是对于测试它会导致我的测试用例失败。 Any ideas on how can I get a fresh version of mockServiceResponse for each test case? 关于如何为每个测试用例获取最新版本的模拟服务响应的任何想法?

您可以使用useThisValue = JSON.parse(JSON.stringify(mockValue))从模拟值复制完整的对象并使用它。

You can leverage beforeEach to set up the test conditions for each test. 您可以利用beforeEach来设置每个测试的测试条件。 You can nest describe and add more beforeEach calls to control how often things are executed. 您可以嵌套describe并添加更多的beforeEach调用,以控制事物执行的频率。

This example will set up your testing module once. 此示例将一次设置您的测试模块。 It will create a "mockServiceResponse" and mock myMethod once per test in the spec. 它将在规范中的每个测试中创建一个“ mockServiceResponse”并模拟一次myMethod

describe('MyComponent', () => {
    const myServiceSpy = jasmine.createSpyObj('MyService',['myMethod'])    

    beforeEach(() => {
        /* 
         * Set up angular testing module
         * Declare your component(s)
         * Provide your spy as the implementation for the service you want to mock
         * This will run once for the entire spec
         */ 
    });

    describe('some more specific description', () => {
       //This will run before each test
       beforeEach(() => {
            let mockServiceResponse = {
                list: [],
                ...
            };
            myServiceSpy .myMethod.and.returnValue( of(mockServiceResponse ) );
        });

        it('does something', () => {
            //run your test
        });

        it('does another thing', () => {
            //run your test
        });
    });
});

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

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