TDD测试模块

Jest测试实例

1.describe

用来描述一个测试用例的作用细节

describe('hello world', () => {
	// ... 用来填写一个个测试用例
})

若仅声明以上部分,则会导致测试失败
Your test suite must contain at least one test.

2.it

Jest测试的基础单元

it('unit test describe',() => {
	//...测试的主体内容
})

在未填写任何内容的情况下该测试用例是可以通过的。

3.测试场景

测试制定dom的文字内容包含字符串’test’

expect(
	<target-dom>
).toMatch('test')

测试指定id的div存在

expect(
	container.querySelector('div#idName')
).not.toBeNull();

测试ol存在并且含有两个子节点

expect(
	container.querySelector('ol')
).not.toBeNull();
expect(
	container.querySelector('ol').children
).toHaveLength(2);

测试li的内容是否符合预期

expect(
	container.querySelector('li')[0].textContent
).toEqual('12:00');
expect(
	container.querySelector('li')[1].textContent
).toEqual('13:00');

li中都包含一个button

expect(
	container.querySelectorAll('li > button')
).toHaveLength(2);
expect(
	container.querySelectorAll('li > button')[0].type
).toEqual('button');

执行React点击事件

import ReactTestUtils from 'react-dom/test-utils';
import MyComponent from './MyComponent';

it('render a component', () => {
	let container;
    const render = component => ReactDOM.render(component, container);
    render(<MyComponent />);
    const button = container.querySelectorAll('button')[1];
    // 模拟点击事件
    ReactTestUtils.Simulate.click(button);
    // 进行点击事件之后的测试
	expect(
		container.textContent
	).toMatch('targetText');
})

验证id为指定id的form标签不为空

const form = id => container.querySelector(`form[id="${id}"]`);
expect(
	form('targetId')
).not.toBeNull();

验证输入框组件存在

const expectToBeInputFieldOfTypeText = formElement => {
    expect(formElement).not.toBeNull();
    expect(formElement.tagName).toEqual('INPUT');
    expect(formElement.type).toEqual('text');
 }
 const element = form('targetForm').elements.<targetName>;
 expectToBeInputFieldOfTypeText(element);

验证label是否符合要求

labelFor = formElement => container.querySelector(`label[for="${formElement}"]`);

expect(
	labelFor('firstName')
).not.toBeNull();

expect(
	labelFor('firstName').textContent
).toEqual('First name');

验证表单提交内容

import ReactTextUtils from 'react-dom/test-utils';

it('submitted firstName', async () => {
	expect.hasAssertions(); // tells Jest that it should expect at least one assertion to occur. Without this line, Jest could happily pass your test if the task queue clears but your event handler was never executed.
	render(
        <CustomerForm
          firstName="Ashley"
          onSubmit={({ firstName }) => 
            expect(firstName).toEqual('Ashley')
          }
        />
      )
      await ReactTestUtils.Simulate.submit(form('customer'));
})

触发元素的onChange方法

it('saves new first name when submitted', async () => {
    expect.hasAssertions();
    render(
      <CustomerForm
        firstName="Ashley"
        onSubmit={({ firstName }) =>
        expect(firstName).toEqual('Jamie')
      }
      />
    );
    await ReactTestUtils.Simulate.change( firstNameField(), {
      target: { value: 'Jamie', name: 'inputName' }
    });
    await ReactTestUtils.Simulate.submit(
      form('customer')
    );
  })

检测渲染出的select选项内容

const selectableServices = ['item1','item2'];
render(
 <AppointmentForm
    selectableServices={selectableServices}
  />
)
const optionNodes = Array.from(
  field('service').childNodes
);
const renderedServices = optionNodes.map(
  node => node.textContent
);
expect(renderedServices).toEqual(
  expect.arrayContaining(selectableServices)
)

4.beforeEach

所有的测试方法可能都需要一些通用的配置,可以将这些通用配置提取到beforeEach中,例如初始化dom或数据

describe('test',() => {
	let container;
	let customer;
	beforeEach(() => {
		container = document.createElement('div');
	})

	it('desc1', () => {
		// ...
	})
	it('desc2', () => {
		// ...
	})
})

猜你喜欢

转载自blog.csdn.net/u010464354/article/details/102788069
TDD