Mocking

一种常见的测试类型是验证部件的用户界面是否按预期渲染,而不必关心部件的底层业务逻辑。但这些测试可能希望断言一些场景,如单击按钮以调用部件的属性方法,并不关心属性方法的实现逻辑,只是希望按预期调用了接口。在这种情况下,可借助类似 Sinon 的 mock 库。

src/widgets/Action.tsx

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. import Button from '@dojo/widgets/button';
  3. import * as css from './Action.m.css';
  4. const factory = create().properties<{ fetchItems: () => void }>();
  5. const Action = factory(function Action({ properties }) {
  6. return (
  7. <div classes={[css.root]}>
  8. <Button key="button" onClick={() => properties().fetchItems()}>
  9. Fetch
  10. </Button>
  11. </div>
  12. );
  13. });
  14. export default Action;

测试当单击按钮后,会调用 properties().fetchItems 方法。

tests/unit/widgets/Action.tsx

  1. const { describe, it } = intern.getInterface('bdd');
  2. import { tsx } from '@dojo/framework/core/vdom';
  3. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  4. import Action from '../../../src/widgets/Action';
  5. import * as css from '../../../src/widgets/Action.m.css';
  6. import Button from '@dojo/widgets/button';
  7. import { stub } from 'sinon';
  8. import { assert } from 'chai';
  9. describe('Action', () => {
  10. const fetchItems = stub();
  11. it('can fetch data on button click', () => {
  12. const WrappedButton = wrap(Button);
  13. const baseAssertion = assertion(() => (
  14. <div classes={[css.root]}>
  15. <WrappedButton key="button" onClick={() => {}}>
  16. Fetch
  17. </WrappedButton>
  18. </div>
  19. ));
  20. const r = renderer(() => <Action fetchItems={fetchItems} />);
  21. r.expect(baseAssertion);
  22. r.property(WrappedButton, 'onClick');
  23. r.expect(baseAssertion);
  24. assert.isTrue(fetchItems.calledOnce);
  25. });
  26. });

在这种情况下,为 Action 部件的 fetchItems 方法提供一个 mock 实现,该方法用于获取数据项。然后使用 WrappedButton 定位到按钮,并触发按钮的 onClick 事件,然后校验 fetchItems 方法仅被调用过一次。

要了解更多 mocking 信息,请阅读 Sinon 文档。

内置的 mock 中间件

有很多 mock 的中间件支持测试使用了相关 Dojo 中间件的部件。Mock 会导出一个 factory,该 factory 创建一个受限作用域的 mock 中间件,会在每个测试中使用。

Mock breakpoint 中间件

使用 @dojo/framework/testing/mocks/middlware/breakpoint 中的 createBreakpointMock 可手动控制 resize 事件来触发断点测试。

考虑下面的部件,当激活 LG 断点时,它会显示附加 h2

src/Breakpoint.tsx

  1. import { tsx, create } from '@dojo/framework/core/vdom';
  2. import breakpoint from '@dojo/framework/core/middleware/breakpoint';
  3. const factory = create({ breakpoint });
  4. export default factory(function Breakpoint({ middleware: { breakpoint } }) {
  5. const bp = breakpoint.get('root');
  6. const isLarge = bp && bp.breakpoint === 'LG';
  7. return (
  8. <div key="root">
  9. <h1>Header</h1>
  10. {isLarge && <h2>Subtitle</h2>}
  11. <div>Longer description</div>
  12. </div>
  13. );
  14. });

使用 mock 的 breakpoint 中间件上的 mockBreakpoint(key: string, contentRect: Partial<DOMRectReadOnly>) 方法,测试可以显式触发一个 resize 事件:

tests/unit/Breakpoint.tsx

  1. const { describe, it } = intern.getInterface('bdd');
  2. import { tsx } from '@dojo/framework/core/vdom';
  3. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  4. import breakpoint from '@dojo/framework/core/middleware/breakpoint';
  5. import createBreakpointMock from '@dojo/framework/testing/mocks/middleware/breakpoint';
  6. import Breakpoint from '../../src/Breakpoint';
  7. describe('Breakpoint', () => {
  8. it('resizes correctly', () => {
  9. const WrappedHeader = wrap('h1');
  10. const mockBreakpoint = createBreakpointMock();
  11. const baseAssertion = assertion(() => (
  12. <div key="root">
  13. <WrappedHeader>Header</WrappedHeader>
  14. <div>Longer description</div>
  15. </div>
  16. ));
  17. const r = renderer(() => <Breakpoint />, {
  18. middleware: [[breakpoint, mockBreakpoint]]
  19. });
  20. r.expect(baseAssertion);
  21. mockBreakpoint('root', { breakpoint: 'LG', contentRect: { width: 800 } });
  22. r.expect(baseAssertion.insertAfter(WrappedHeader, () => [<h2>Subtitle</h2>]);
  23. });
  24. });

Mock focus 中间件

使用 @dojo/framework/testing/middleware/focus 中的 createFocusMock 可手动控制 focus 中间件何时报告指定 key 的节点获取了焦点。

考虑下面的部件:

src/FormWidget.tsx

  1. import { tsx, create } from '@dojo/framework/core/vdom';
  2. import focus, { FocusProperties } from '@dojo/framework/core/middleware/focus';
  3. import * as css from './FormWidget.m.css';
  4. export interface FormWidgetProperties extends FocusProperties {}
  5. const factory = create({ focus }).properties<FormWidgetProperties>();
  6. export const FormWidget = factory(function FormWidget({ middleware: { focus } }) {
  7. return (
  8. <div key="wrapper" classes={[css.root, focus.isFocused('text') ? css.focused : null]}>
  9. <input type="text" key="text" value="focus me" />
  10. </div>
  11. );
  12. });

通过调用 focusMock(key: string | number, value: boolean),就可以在测试时控制 focus 中间件中 isFocused 方法的返回值。

tests/unit/FormWidget.tsx

  1. const { describe, it } = intern.getInterface('bdd');
  2. import { tsx } from '@dojo/framework/core/vdom';
  3. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  4. import focus from '@dojo/framework/core/middleware/focus';
  5. import createFocusMock from '@dojo/framework/testing/mocks/middleware/focus';
  6. import * as css from './FormWidget.m.css';
  7. describe('Focus', () => {
  8. it('adds a "focused" class to the wrapper when the input is focused', () => {
  9. const focusMock = createFocusMock();
  10. const WrappedRoot = wrap('div');
  11. const baseAssertion = assertion(() => (
  12. <WrappedRoot key="wrapper" classes={[css.root, null]}>
  13. <input type="text" key="text" value="focus me" />
  14. </WrappedRoot>
  15. ));
  16. const r = renderer(() => <FormWidget />, {
  17. middleware: [[focus, focusMock]]
  18. });
  19. r.expect(baseAssertion);
  20. focusMock('text', true);
  21. r.expect(baseAssertion.setProperty(WrappedRoot, 'classes', [css.root, css.focused]));
  22. });
  23. });

Mock iCache 中间件

使用 @dojo/framework/testing/mocks/middleware/icache 中的 createICacheMiddleware,能让测试代码直接访问缓存中的项,而此 mock 为被测的小部件提供了足够的 icache 功能。当使用 icache 异步获取数据时特别有用。直接访问缓存让测试可以 await 部件,就如 await promise 一样。

考虑以下部件,从一个 API 获取数据:

src/MyWidget.tsx

  1. import { tsx, create } from '@dojo/framework/core/vdom';
  2. import { icache } from '@dojo/framework/core/middleware/icache';
  3. import fetch from '@dojo/framework/shim/fetch';
  4. const factory = create({ icache });
  5. export default factory(function MyWidget({ middleware: { icache } }) {
  6. const value = icache.getOrSet('users', async () => {
  7. const response = await fetch('url');
  8. return await response.json();
  9. });
  10. return value ? <div>{value}</div> : <div>Loading</div>;
  11. });

使用 mock 的 icache 中间件测试异步结果很简单:

tests/unit/MyWidget.tsx

  1. const { describe, it, afterEach } = intern.getInterface('bdd');
  2. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  3. import { tsx } from '@dojo/framework/core/vdom';
  4. import * as sinon from 'sinon';
  5. import global from '@dojo/framework/shim/global';
  6. import icache from '@dojo/framework/core/middleware/icache';
  7. import createICacheMock from '@dojo/framework/testing/mocks/middleware/icache';
  8. import MyWidget from '../../src/MyWidget';
  9. describe('MyWidget', () => {
  10. afterEach(() => {
  11. sinon.restore();
  12. });
  13. it('test', async () => {
  14. // stub the fetch call to return a known value
  15. global.fetch = sinon.stub().returns(Promise.resolve({ json: () => Promise.resolve('api data') }));
  16. const WrappedRoot = wrap('div');
  17. const baseAssertion = assertion(() => <WrappedRoot>Loading</WrappedRoot>);
  18. const mockICache = createICacheMock();
  19. const r = renderer(() => <Home />, { middleware: [[icache, mockICache]] });
  20. r.expect(baseAssertion);
  21. // await the async method passed to the mock cache
  22. await mockICache('users');
  23. r.expect(baseAssertion.setChildren(WrappedRoot, () => ['api data']));
  24. });
  25. });

Mock intersection 中间件

使用 @dojo/framework/testing/mocks/middleware/intersection 中的 createIntersectionMock 可 mock 一个 intersection 中间件。要设置从 intersection mock 中返回的期望值,需要调用创建的 mock intersection 中间件,并传入 key 和期望的 intersection 详情。

考虑以下部件:

  1. import { create, tsx } from '@dojo/framework/core/vdom';
  2. import intersection from '@dojo/framework/core/middleware/intersection';
  3. const factory = create({ intersection });
  4. const App = factory(({ middleware: { intersection } }) => {
  5. const details = intersection.get('root');
  6. return <div key="root">{JSON.stringify(details)}</div>;
  7. });

使用 mock 的 intersection 中间件:

  1. import { tsx } from '@dojo/framework/core/vdom';
  2. import createIntersectionMock from '@dojo/framework/testing/mocks/middleware/intersection';
  3. import intersection from '@dojo/framework/core/middleware/intersection';
  4. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  5. import MyWidget from './MyWidget';
  6. describe('MyWidget', () => {
  7. it('test', () => {
  8. // create the intersection mock
  9. const intersectionMock = createIntersectionMock();
  10. // pass the intersection mock to the renderer so it knows to
  11. // replace the original middleware
  12. const r = renderer(() => <App key="app" />, { middleware: [[intersection, intersectionMock]] });
  13. const WrappedRoot = wrap('div');
  14. const assertion = assertion(() => (
  15. <WrappedRoot key="root">{`{"intersectionRatio":0,"isIntersecting":false}`}</WrappedRoot>
  16. ));
  17. // call renderer.expect as usual, asserting the default response
  18. r.expect(assertion);
  19. // use the intersection mock to set the expected return
  20. // of the intersection middleware by key
  21. intersectionMock('root', { isIntersecting: true });
  22. // assert again with the updated expectation
  23. r.expect(assertion.setChildren(WrappedRoot, () => [`{"isIntersecting": true }`]));
  24. });
  25. });

Mock node 中间件

使用 @dojo/framework/testing/mocks/middleware/node 中的 createNodeMock 可 mock 一个 node 中间件。要设置从 node mock 中返回的期望值,需要调用创建的 mock node 中间件,并传入 key 和期望的 DOM node。

  1. import createNodeMock from '@dojo/framework/testing/mocks/middleware/node';
  2. // 创建一个 mock node 的中间件
  3. const mockNode = createNodeMock();
  4. // mock 一个 DOM 节点
  5. const domNode = {};
  6. // 调用 mock 中间件,并传入 key 和将返回的 DOM
  7. mockNode('key', domNode);

Mock resize 中间件

使用 @dojo/framework/testing/mocks/middleware/resize 中的 createResizeMock 可 mock 一个 resize 中间件。要设置从 resize mock 中返回的期望值,需要调用创建的 mock resize 中间件,并传入 key 和期望的容纳内容的矩形区域。

  1. const mockResize = createResizeMock();
  2. mockResize('key', { width: 100 });

考虑以下部件:

  1. import { create, tsx } from '@dojo/framework/core/vdom'
  2. import resize from '@dojo/framework/core/middleware/resize'
  3. const factory = create({ resize });
  4. export const MyWidget = factory(function MyWidget({ middleware }) => {
  5. const { resize } = middleware;
  6. const contentRects = resize.get('root');
  7. return <div key="root">{JSON.stringify(contentRects)}</div>;
  8. });

使用 mock 的 resize 中间件:

  1. import { tsx } from '@dojo/framework/core/vdom';
  2. import createResizeMock from '@dojo/framework/testing/mocks/middleware/resize';
  3. import resize from '@dojo/framework/core/middleware/resize';
  4. import renderer, { assertion, wrap } from '@dojo/framework/testing/renderer';
  5. import MyWidget from './MyWidget';
  6. describe('MyWidget', () => {
  7. it('test', () => {
  8. // 创建一个 mock resize 的中间件
  9. const resizeMock = createResizeMock();
  10. // 将 resize mock 中间件传给测试渲染器,
  11. // 这样测试渲染器就知道要替换掉原来的中间件
  12. const r = renderer(() => <App key="app" />, { middleware: [[resize, resizeMock]] });
  13. const WrappedRoot = wrap('div');
  14. const baseAssertion = assertion(() => <div key="root">null</div>);
  15. // 像平常一样调用 renderer.expect
  16. r.expect(baseAssertion);
  17. // 使用 mock 的 resize 中间件,通过指定 key 值,
  18. // 设置期望 resize 中间件返回的结果
  19. resizeMock('root', { width: 100 });
  20. // 用更新后的期望值再断言一次
  21. r.expect(baseAssertion.setChildren(WrappedRoot, () [`{"width":100}`]);)
  22. });
  23. });

Mock Store 中间件

使用 @dojo/framework/testing/mocks/middleware/store 中的 createMockStoreMiddleware 可 mock 一个强类型的 store 中间件,也支持 mock process。为了 mock 一个 store 的 process,可传入一个由原始 store process 和 stub process 组成的元组。中间件会改为调用 stub,而不是调用原始的 process。如果没有传入 stub,中间件将不会调用所有的 process。

要修改 mock store 中的值,需要调用 mockStore,并传入一个返回一组 store 操作的函数。这将注入 store 的 path 函数,以创建指向需要修改的状态的指针。

  1. mockStore((path) => [replace(path('details', { id: 'id' })]);

考虑以下部件:

src/MyWidget.tsx

  1. import { create, tsx } from '@dojo/framework/core/vdom'
  2. import { myProcess } from './processes';
  3. import MyState from './interfaces';
  4. // 应用程序的 store 中间件通过 state 接口来指定类型
  5. // 示例:`const store = createStoreMiddleware<MyState>();`
  6. import store from './store';
  7. const factory = create({ store }).properties<{ id: string }>();
  8. export default factory(function MyWidget({ properties, middleware: store }) {
  9. const { id } = properties();
  10. const { path, get, executor } = store;
  11. const details = get(path('details');
  12. let isLoading = get(path('isLoading'));
  13. if ((!details || details.id !== id) && !isLoading) {
  14. executor(myProcess)({ id });
  15. isLoading = true;
  16. }
  17. if (isLoading) {
  18. return <Loading />;
  19. }
  20. return <ShowDetails {...details} />;
  21. });

使用 mock 的 store 中间件:

tests/unit/MyWidget.tsx

  1. import { tsx } from '@dojo/framework/core/vdom'
  2. import createMockStoreMiddleware from '@dojo/framework/testing/mocks/middleware/store';
  3. import renderer from '@dojo/framework/testing/renderer';
  4. import { myProcess } from './processes';
  5. import MyWidget from './MyWidget';
  6. import MyState from './interfaces';
  7. import store from './store';
  8. // 导入 stub/mock 库,可以不是 sinon
  9. import { stub } from 'sinon';
  10. describe('MyWidget', () => {
  11. it('test', () => {
  12. const properties = {
  13. id: 'id'
  14. };
  15. const myProcessStub = stub();
  16. // 类型安全的 mock store 中间件
  17. // 为 mock 的 process 传入一组 `[originalProcess, stub]` 元组
  18. // 将忽略未传入 stub/mock 的 process
  19. const mockStore = createMockStoreMiddleware<MyState>([[myProcess, myProcessStub]]);
  20. const r = renderer(() => <MyWidget {...properties} />, {
  21. middleware: [[store, mockStore]]
  22. });
  23. r.expect(/* 断言 `Loading`*/);
  24. // 重新断言 stubbed process
  25. expect(myProcessStub.calledWith({ id: 'id' })).toBeTruthy();
  26. mockStore((path) => [replace(path('isLoading', true)]);
  27. r.expect(/* 断言 `Loading`*/);
  28. expect(myProcessStub.calledOnce()).toBeTruthy();
  29. // 使用 mock 的 store 来在 store 上应用操作
  30. mockStore((path) => [replace(path('details', { id: 'id' })]);
  31. mockStore((path) => [replace(path('isLoading', true)]);
  32. r.expect(/* 断言 `ShowDetails` */);
  33. properties.id = 'other';
  34. r.expect(/* 断言 `Loading`*/);
  35. expect(myProcessStub.calledTwice()).toBeTruthy();
  36. expect(myProcessStub.secondCall.calledWith({ id: 'other' })).toBeTruthy();
  37. mockStore((path) => [replace(path('details', { id: 'other' })]);
  38. r.expect(/* 断言 `ShowDetails`*/);
  39. });
  40. });

Mock validity 中间件

使用 @dojo/framework/testing/mocks/middleware/validity 中的 createValidityMock 可 mock 一个 validity 中间件,可以在测试用控制 get 方法的返回值。

考虑以下示例:

src/FormWidget.tsx

  1. import { tsx, create } from '@dojo/framework/core/vdom';
  2. import validity from '@dojo/framework/core/middleware/validity';
  3. import icache from '@dojo/framework/core/middleware/icache';
  4. import * as css from './FormWidget.m.css';
  5. const factory = create({ validity, icache });
  6. export const FormWidget = factory(function FormWidget({ middleware: { validity, icache } }) {
  7. const value = icache.getOrSet('value', '');
  8. const { valid, message } = validity.get('input', value);
  9. return (
  10. <div key="root" classes={[css.root, valid === false ? css.invalid : null]}>
  11. <input type="email" key="input" value={value} onchange={(value) => icache.set('value', value)} />
  12. {message ? <p key="validityMessage">{message}</p> : null}
  13. </div>
  14. );
  15. });

使用 validityMock(key: string, value: { valid?: boolean, message?: string; }),可以在测试中控制 validity mock 中 get 方法的返回值。

tests/unit/FormWidget.tsx

  1. const { describe, it } = intern.getInterface('bdd');
  2. import { tsx } from '@dojo/framework/core/vdom';
  3. import renderer, { assertion } from '@dojo/framework/testing/renderer';
  4. import validity from '@dojo/framework/core/middleware/validity';
  5. import createValidityMock from '@dojo/framework/testing/mocks/middleware/validity';
  6. import * as css from './FormWidget.m.css';
  7. describe('Validity', () => {
  8. it('adds the "invalid" class to the wrapper when the input is invalid and displays a message', () => {
  9. const validityMock = createValidityMock();
  10. const r = renderer(() => <FormWidget />, {
  11. middleware: [[validity, validityMock]]
  12. });
  13. const WrappedRoot = wrap('div');
  14. const baseAssertion = assertion(() => (
  15. <WrappedRoot key="root" classes={[css.root, null]}>
  16. <input type="email" key="input" value="" onchange={() => {}} />
  17. </WrappedRoot>
  18. ));
  19. r.expect(baseAssertion);
  20. validityMock('input', { valid: false, message: 'invalid message' });
  21. const invalidAssertion = baseAssertion
  22. .append(WrappedRoot, () => [<p key="validityMessage">invalid message</p>])
  23. .setProperty(WrappedRoot, 'classes', [css.root, css.invalid]);
  24. r.expect(invalidAssertion);
  25. });
  26. });

自定义 Mock 中间件

已提供的 mock 中间件并未覆盖所有的测试场景。也可以创建自定义的 mock 中间件。模拟中间件应该提供一个可重载的接口。无参的重载应该返回中间件的实现,它将被注入到被测的部件中。根据需要创建其他重载,以便为测试提供接口。

例如,参考框架中的 icache mock。这个 mock 提供了以下重载:

  1. function mockCache(): MiddlewareResult<any, any, any>;
  2. function mockCache(key: string): Promise<any>;
  3. function mockCache(key?: string): Promise<any> | MiddlewareResult<any, any, any>;

接收 key 的重载让测试可以直接访问缓存中的项。这个简短的示例演示了模拟如何同时包含中间件实现和测试接口;这使得 mock 可以在部件和测试之间的搭起桥梁。

  1. export function createMockMiddleware() {
  2. const sharedData = new Map<string, any>();
  3. const mockFactory = factory(() => {
  4. // 实际的中间件实现;使用 `sharedData` 来搭起桥梁
  5. return {
  6. get(id: string): any {},
  7. set(id: string, value: any): void {}
  8. };
  9. });
  10. function mockMiddleware(): MiddlewareResult<any, any, any>;
  11. function mockMiddleware(id: string): any;
  12. function mockMiddleware(id?: string): any | Middleware<any, any, any> {
  13. if (id) {
  14. // 直接访问 `sharedData`
  15. return sharedData.get(id);
  16. } else {
  17. // 向部件提供中间件的实现
  18. return mockFactory();
  19. }
  20. }
  21. }

framework/src/testing/mocks/middlware 中有很多完整的模拟示例可供参考。