2017-11-28 42 views
2

React Native 프로젝트의 단위 테스트를 작성할 때 다른 플랫폼을 기반으로 다른 스냅 샷을 테스트 할 수 있기를 원합니다.React Native : Jest Mocking Platform

먼저 jest.mock을 모의 Platform으로 시도했지만 비동기로 보입니다. 이 방법은 두 개의 개별 파일이있을 때 작동하지만 가능하면 모든 파일을 한 파일에 보관하는 것을 선호합니다.

나는 때문에 문서에서이 조각의 jest.doMock을 시도 : 바벨-농담을 사용하는 경우

, 자동으로 코드 블록의 상단에 게양된다 조롱 호출합니다. 이 동작을 명시 적으로 피하려면이 방법을 사용하십시오. https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

그러나 여전히 바람직하지 않은 결과가 표시됩니다. 내가 console.log에서 안드로이드 테스트를 볼 때 Platform.OS은 무엇이든간에 처음으로 doMock으로 설정되었습니다. 나는 그 http://facebook.github.io/jest/docs/en/setup-teardown.html#scoping

describe('ios test',() => { 
    it('renders ui correctly',() => { 
    jest.doMock('Platform',() => { 
     const Platform = require.requireActual('Platform'); 
     Platform.OS = 'ios'; 
     return Platform; 
    }); 
    const wrapper = shallow(<SomeComponent />); 
    const tree = renderer.create(wrapper).toJSON(); 
    expect(tree).toMatchSnapshot(); 
    }); 
}); 

describe('android test',() => { 
    it('renders ui correctly',() => { 
    jest.doMock('Platform',() => { 
     const Platform = require.requireActual('Platform'); 
     Platform.OS = 'android'; 
     return Platform; 
    }); 
    const wrapper = shallow(<SomeComponent />); 
    const tree = renderer.create(wrapper).toJSON(); 
    expect(tree).toMatchSnapshot(); 
    }); 
}); 

나는 동일한 파일에 시험을위한 모의 플랫폼을 변경하는 방법에 어떤 아이디어를 범위 지정에 도움이 될 생각 변경할 수 없기

나는 또한 describebeforeEach에서 모의을 포장하려고?

답변

1

another question에서이 문제를 해결하는 방법에 대한 제안이 많이 있지만, 그들 중 누구도 당신이이 같은 요구 사항 (다른 OS를위한 테스트합니다 같은 스위트 파일 및에 주어진 어느 날 위해 일하지 하나의 시험 실행).

나는 결국 시험에서 예상대로 조롱 할 수있는 다소 투박한 사소한 도우미 기능을 주위 일 - 뭔가 같은 :

export function getOS() { 
    return Platform.OS; 
} 

이 그것을 사용하는 대신 다음 코드에서 Platform.OS, 단순히 모의 그것은 당신의 시험에서, 예.

it('does something on Android',() => { 
    helpers.getOS = jest.fn().mockImplementationOnce(() => 'android'); 
    // ... 
} 

그 트릭을 수행했습니다. 아이디어에 대한 크레딧은 this guy입니다.