简体   繁体   中英

Angular 6 unit testing static mock response

I am testing an Angular component which calls a service method. 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. 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. 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. You can nest describe and add more beforeEach calls to control how often things are executed.

This example will set up your testing module once. It will create a "mockServiceResponse" and mock myMethod once per test in the spec.

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
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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